id
stringlengths
3
8
content
stringlengths
100
981k
9943888
def _generate_function(identifier): class Function: def __init__(self, field='*'): self.field = field def evaluate(self): if hasattr(self.field, 'evaluate'): field = self.field.evaluate() else: field = self.field return...
9943898
from typing import Optional from botocore.client import BaseClient from typing import Dict from typing import Union from botocore.paginate import Paginator from botocore.waiter import Waiter from typing import List class Client(BaseClient): def can_paginate(self, operation_name: str = None): pass def...
9943948
import json import os import shapely.geometry with open(os.path.join(os.path.dirname(__file__), "constants.json"), encoding="utf-8") as file: constants = json.load(file) constants["mid_lane"] = shapely.geometry.Polygon(constants["mid_lane"]) constants["top_lane"] = shapely.geometry.Polygon(constants["top_lane"])...
9943953
import os import json import logging import requests # LEDGER_URL = os.environ.get('LEDGER_URL') # if not LEDGER_URL: # raise Exception('LEDGER_URL must be set.') class ClaimParser(object): """ Parses a generic claim. """ def __init__(self, claim: str) -> None: self.__logger = logging.getLo...
9943970
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.4' setup(name='rebar', version=version + '+eventbrite.2', description="", ...
9943978
import numpy as np def linear_divide(x, a, b, c): """ Find the best two dividing point for a linear array made up with three different characters. """ n = len(x) ab_penalty = (np.append(0, (np.array(x) == b).cumsum()) + np.append((np.array(x) == a)[::-1].cumsum()[::-1], 0)) b...
9943986
from pal.filter.abstract_filter import AbstractFilter class ActivityMonitorRegisterFilter(AbstractFilter): @property def description(self): return "activity monitor registers" def do_filter(self, reg): regname = reg.name.lower() if(regname.startswith("am") and not regname.startswit...
9944007
import tensorlayerx as tlx from tensorlayerx.nn.layers import Conv2d, ZeroPad2d, MaxPool2d, ReLU import numpy as np class FrozenBatchNorm2D(tlx.nn.Module): def __init__(self, backbone_bn_shape, eps=1e-5, **kwargs): super().__init__(**kwargs) self.eps = eps self.weight = self._get_weights(...
9944010
import discord from discord.ext import commands import asyncio import subprocess import logging import aiohttp from bs4 import BeautifulSoup from arsenic import get_session, services, browsers logger = logging.getLogger(__name__) class DocInfo(commands.Cog): def __init__(self, bot): self.bot = ...
9944082
from __future__ import absolute_import, division, print_function from semantic_version import Spec, Version def versions(versions_str, stable=False): if stable: return [Version(x) for x in versions_str if len(x.split("-")) == 1] else: return [Version(x) for x in versions_str] def last_versi...
9944083
import os import numpy as np from keras.applications import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input height = 150 width = 150 def preprocess_image(path): img = image.load_img(path, target_size = (height, width)) a = image.img_to_array(img) a = np.e...
9944169
import sys from collections import defaultdict groups, people, my_groups = defaultdict(set), {}, {} test_cases = open(sys.argv[1], "r") for test in test_cases: name, friend, group = test.rstrip().split(":") for g in group.split(","): if g: groups[g].add(name) my_groups[name] = set(gro...
9944177
import pyspeckit import numpy as np from pyspeckit.spectrum.models import inherited_voigtfitter # This example uses scipy try: import scipy except ImportError: exit # technically, the voigt fitter works as a singlefitter (i.e., you can fit the # background level and the peak simultaneously) # in practice, how...
9944206
import time from functools import partial from mpf.core.logging import LogMixin from mpf.tests.MpfGameTestCase import MpfGameTestCase class BenchmarkLightShows(MpfGameTestCase): def get_config_file(self): return 'config.yaml' def get_machine_path(self): return 'benchmarks/machine_files/sho...
9944294
from boa3.builtin import public from boa3.builtin.interop.runtime import check_witness as CheckWitness from boa3.builtin.type import ECPoint @public def Main(script_hash: ECPoint) -> bool: return CheckWitness(script_hash)
9944297
import logging import random import sys from collections import OrderedDict import numpy as np import torch def reset_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True def to_cuda(obj): if to...
9944370
import tkinter as tk from tklog import winlogHandler import logging if __name__ == '__main__': root = tk.Tk() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s: %(message)s') winhandler = winlogHandler(root=root, ...
9944546
from .permute import * from .swap import * from .halfcleaner import * from .brick import * from .evenodd import * from .bitonic import *
9944591
from .bootstrap import get_config_space, get_available_config_spaces from . import resnet from . import text_classification
9944621
from ramda import * from ramda.private.asserts import * import json def unapply_test(): assert_equal(unapply(json.dumps)(1, 2, 3), "[1, 2, 3]")
9944649
import os import operator import string from random import shuffle from collections import Counter import json import pickle import nltk from nltk.tokenize import TweetTokenizer from nltk.stem import WordNetLemmatizer __author__ = "<NAME> and <NAME>" def tokenize(data): """ Tokenization. Tokenize and lemmatize...
9944705
from ...language import Language class MultiLanguage(Language): """Language class to be used for models that support multiple languages. This module allows models to specify their language ID as 'xx'. """ lang = "xx" __all__ = ["MultiLanguage"]
9944734
from flask_restly.decorator import resource, put from flask_restly import FlaskRestly from flask import Flask def test_should_return_201_code_when_content_provided_and_code_not_provided(): app = Flask(__name__) FlaskRestly(app) @resource(name='test') class SomeResource: @put('/<int:id>') ...
9944748
from mayan.apps.testing.tests.base import GenericViewTestCase from ..events import event_key_created, event_key_downloaded from ..models import Key from ..permissions import ( permission_key_delete, permission_key_download, permission_key_upload ) from .literals import TEST_KEY_PRIVATE_FINGERPRINT from .mixins im...
9944759
import math from scipy.optimize import minimize from scipy import interpolate try: from numba import njit NJIT = True except ImportError: NJIT = False import numpy as np # Define constants A = [7.24032, -2.84383e-3, 2.75660e-5] B = [8.63186, -3.31977e-3, 2.37170e-5] # Gravitational constant G = 0.052 # W...
9944763
from utils_aip import get_face_attributes if __name__ == "__main__": filePath = "../images/wanghong.jpg" attr = get_face_attributes(filePath) print(attr)
9944867
import sublime import os import fnmatch import shutil import json try: from . import tools except ValueError: from package_sync_helpers import tools prompt_parameters = {} def create_temp_backup(): psync_settings = tools.get_psync_settings() try: if os.path.exists(tools.temp_backup_folder)...
9944877
class Script(object): def execute(self): pass @staticmethod def get_config(): return {'configurations': {'node.properties': {}, 'jvm.config': {'jvm.config': ''}, 'config.properties': {}, 'connectors.properties': {'connector...
9944947
import bisect import supriya.commands from supriya.nonrealtime.bases import SessionObject class Buffer(SessionObject): """ A non-realtime buffer. """ ### CLASS VARIABLES ### __documentation_section__ = "Session Objects" __slots__ = ( "_buffer_group", "_channel_count", ...
9944958
import argparse def model_opts(parser): """ These options are passed to the construction of the model. Be careful with these as they will be used during translation. """ # Model options # Embedding Options parser.add_argument('-word_vec_size', type=int, default=250, ...
9944974
import pandas as pd from cadCAD.engine import ExecutionMode, ExecutionContext, Executor from cadCAD.configuration import Experiment from cadCAD import configs def run(drop_midsteps: bool=True) -> pd.DataFrame: exec_mode = ExecutionMode() exec_context = ExecutionContext(exec_mode.local_mode) run = Executor...
9945005
from pydantic import BaseModel from typing import List, Optional class RoleBase(BaseModel): role_id: Optional[str] = None role_name: str role_desc: str user_count: Optional[int] = None class RoleList(BaseModel): roles: List[RoleBase] = [] class RoleEditUsers(BaseModel): # 修改成员模型 role_i...
9945147
from .utils import * from .indicator_calculator import IndicatorCalculator from .current_ratio import CurrentRatio from .liquidity_ratio import LiquidityRatio from .current_debtors_collection_rate import CurrentDebtorsCollectionRate from .cash_balance import CashBalance from .cash_coverage import CashCoverage from .ope...
9945196
from examples.example_imports import * num_line1 = NumberLine(x_range=[0, 5, 1], include_numbers=True, include_tip=True, tip_config={"width": 0.25, "length": 0.35}, ) class A1(EagerModeScene): def __init__(self): super(A1, self).__init__(screen_size=Size.bigg...
9945198
from vpack import breakpt for i in range(10): print(i) breakpt.at(8) # break at i = 7 breakpt.at(5) # break at i = 4 for i in range(6): print(i) if i == 2: breakpt.disable() # disable breakpt if i == 4: breakpt.enable() # enable breakpt breakpt.always() # break at i = 0, 1, 4, 5 breakpt.o...
9945235
from .filereader import FileReader def load(file, encoding='utf-8'): reader = FileReader(file, encoding) return reader.read()
9945263
import numpy as np import pytest from Starfish.constants import hc_k from Starfish.models.kernels import global_covariance_matrix, local_covariance_matrix class TestKernels: def test_global_matrix(self): wave = np.linspace(1e4, 2e4, 1000) amp = 100 lengthscale = 1 T = 6000 ...
9945286
import sys import os import pytest sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import votelib.measure CANADA_2015_VOTES = { 'Liberal': 6943276, 'Conservative': 5613614, 'New Democratic': 3470350, 'Bloc Québécois': 821144, 'Green': 602944, 'Other': 91837, } ...
9945306
from __future__ import division import os import sys import time import glob import logging from tqdm import tqdm import torch import torch.nn as nn import torch.utils import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision.transforms as transforms from torch.utils.data im...
9945317
import IPython.nbformat.current as current class NotebookParser(object): """Parser for IPython Notebook files.""" def parse(self, json_data): """Parse a notebook .ipynb file. Parameters ---------- json_data : file A file handle for an .ipynb file. Returns ...
9945323
from collections import Counter import random def mmap(f, l): return list(map(f, l)) colours = ['S', 'H', 'D', 'C'] blotkarz_num = list(map(lambda x: str(x), list(range(10)))) figurant_num = ['A', 'K', 'D', 'J'] blotkarz_set = [] figurant_set = [] for c in colours: for n in blotkarz_num: blotkarz_s...
9945325
from time import sleep def method_in_another_file(some_number: int): print('File contents are stored as they were at the moment of the recording.') print('For easy navigation, press G to open graph panel') print('Graph will give overview of method calls and their approximate duration.') print('Check...
9945355
from .decorators import endpoint from ..definitions.types import TransactionID from ..endpoints.annotations import FromTime from ..endpoints.annotations import FromTransactionID from ..endpoints.annotations import PageSize from ..endpoints.annotations import ToTime from ..endpoints.annotations import ToTransactionID fr...
9945366
from unittest import mock from django.test import SimpleTestCase, override_settings from hypha.apply.utils.templatetags.webpack_tags import render_bundle class WebpackTagsTestCase(SimpleTestCase): @override_settings(ENABLE_WEBPACK_BUNDLES=True) def test_render_bundle_calls_webpack_loader_when_enabled(self)...
9945396
import mock import os import unittest from deepstar.filesystem.frame_set_sub_dir import FrameSetSubDir class TestFrameSetSubDir(unittest.TestCase): """ This class tests the FrameSetSubDir class. """ def test_path(self): with mock.patch.dict(os.environ, {'DEEPSTAR_PATH': 'test'}): ...
9945405
class Solution(object): def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ res = 0 j = 0 k = 2 count_map = dict() for i in range(len(s)): while (j < len(s) and (len(count_map) < k or (len(count_map) ...
9945407
from datetime import datetime from decimal import Decimal from enum import Enum from typing import Dict, List, Optional, Tuple from uuid import UUID from pydantic import BaseModel, EmailStr, PrivateAttr class Entity(BaseModel): ... class IDEntity(Entity): id: UUID class UUIDEntity(Entity): uuid: UUID...
9945416
from ..._protos.public.registry import RegistryService_pb2 from . import _LockLevel class Open(_LockLevel): """ Changes to the model version are allowed. Examples -------- .. code-block:: python from verta.registry import lock reg_model = client.create_registered_model("My Model...
9945420
from abc import ABC, abstractmethod from open3d.cpu.pybind.geometry import Geometry3D class BaseGeometry(ABC): @abstractmethod def get(self) -> Geometry3D: pass
9945469
import datetime from dataclasses import dataclass from typing import Optional from ..type import ID from ..enums import JobResultAction, JobResultActionReason @dataclass class JobResult: """Represents a download result from a job. .. versionadded:: 1.5.0 """ id: ID action: JobResultAction r...
9945505
from __future__ import absolute_import, division, print_function, unicode_literals from mprpc import RPCClient from urlserver.protos import urlserver_pb2 from .config import config from .url import URL from . import py2_xrange class URLClientRemote(object): """ The URLClient takes URLs and sends them to the URL...
9945517
import site from os.path import dirname, join from importlib import import_module site.addsitedir(join(dirname(dirname(__file__)), "functions")) schedule_update = import_module("schedule-update") def test_handler(mocker, handler): schedule_update.GSHEETS_DOC_ID = "mock_doc_id" mock_gsheets = mocker.patch.ob...
9945560
import argparse from os import sys import random from sys import path from os import getcwd import os, sys, inspect, pprint import time # this is a hack to get the hpe driver module # and it's utils module on the search path. cmd_folder = os.path.realpath(os.path.abspath("..") ) if cmd_folder not in sys.path: sys...
9945566
import shutil import pytest from jupytext import read from jupytext.cli import jupytext from .utils import requires_ir_kernel, requires_nbconvert, skip_on_windows @requires_nbconvert @skip_on_windows def test_pipe_nbconvert_execute(tmpdir): tmp_ipynb = str(tmpdir.join("notebook.ipynb")) tmp_py = str(tmpdir...
9945576
import logging from . import winansi, pdfdoc, macroman, standard from .codec import Codec known_base_codecs = (winansi.WinAnsiCodec, pdfdoc.PdfDocCodec, macroman.MacRomanCodec, standard.StandardCodec) base_encodings_map = {c.name: c for c in known_base_codecs} implicit_base_encoding = "StandardEncoding" def Differ...
9945580
import sqlalchemy as sa from sqlalchemy.dialects import postgresql __all__ = ['post', 'comment', 'tag'] meta = sa.MetaData() post = sa.Table( 'post', meta, sa.Column('id', sa.Integer, nullable=False), sa.Column('title', sa.String(200), nullable=False), sa.Column('teaser', sa.String(500), nullable=F...
9945611
import os import sys import logging import cPickle import random import numpy as np import time from paddle.trainer.PyDataProvider2 import * logging.basicConfig( format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s', ) logger = logging.getLogger('paddle_data_provider') logger.setL...
9945642
import math from hippy.builtin import wrap from hippy.builtin import StringArg from hippy.builtin import BoolArg from hippy.builtin import LongArg from hippy.builtin import Optional from rpython.rlib import rsocket from rpython.rlib.rstring import StringBuilder from hippy.module.date.funcs import _strftime from hippy.o...
9945670
import sys, unittest, redis, yaml, time from itertools import izip sys.path.append('../lib/') from policy import PolicyData, Policy from utils import ThemisMetaData, Features class FeaturesTestCase(unittest.TestCase): """ Tests for Policy class """ FEATURES_CUSTOM_CALLBACK = { 'statisticsFeature' : bool,...
9945718
import dash import dash_html_components as html import dash_core_components as dcc import json import re import swiftclient import plotly.graph_objects as go import pandas as pd import dash_leaflet as dl from bs4 import BeautifulSoup import dash_dangerously_set_inner_html import folium import numpy as np # Read config...
9945789
from .._tier0 import Image from .._tier0 import create_none from .._tier0 import plugin_function @plugin_function(output_creator=create_none) def regionprops(labelmap : Image, intensity_image : Image = None, cache : bool = True, extra_properties = []): """Convert the intensity image and the corresponding label ima...
9945859
import nepali_datetime class TestStrftime: def test_strftime_date(self): dt = nepali_datetime.date(2077, 6, 4) assert dt.strftime("%m/%d/%Y") == "06/04/2077" assert dt.strftime("%A of %B %d %y") == "Sunday of Aswin 04 77" assert dt.strftime("%a %b") == "Sun Asw" dt = nepa...
9945898
import torch class Subsample(object): r"""Samples only the positions and descriptors that are set in data.sample_idx. """ def __init__(self): return def __call__(self, data): assert hasattr(data, 'sample_idx') sample_idx = data.sample_idx data.pos = data.pos[sample_id...
9945909
import numpy POSSIBLE_REACTION_ARROWS = ('=', '=>', '<=>', '->', '<->', u'\u2192', u'\u21CC') R = 8.31e-3 # kJ/(K*mol) F = 0.096485 # (kJ/mol)/mV JOULES_PER_CAL = 4.184 # kJ/mol, formation energy of Mg2+ MG_FORMATION_ENERGY = -455.3 DEFAULT_TEMP = 298.15 # K DEFAULT_IONIC_STRENGTH = ...
9945913
a = [] c = 0 for j in range(0, 10): for i in range(0, 500000): a.append(1) for j in range(0, 10): for i in range(0, 500000): c = c + a[i] print(c)
9945928
from django.shortcuts import render # Create your views here. import json from django.http import JsonResponse, HttpResponse from .detection import getresponse def output(request, in_text): response = getresponse(in_text) res = json.loads(response) return JsonResponse({ "language_code": res['results'][0]['lan...
9945931
import skimage.io as io import skimage.transform as skt import numpy as np from PIL import Image from src.models.class_patcher import patcher from src.utils.imgproc import * from skimage.color import rgb2hsv, hsv2rgb class patcher(patcher): def __init__(self, body='./body/body_shaon.png', **options): supe...
9945940
import numpy as np def concordance_index(event_times, predicted_scores, event_observed=None): """ Code adapted from https://github.com/CamDavidsonPilon/lifelines/blob/master/lifelines/utils/concordance.py to account for missing values in the context of the HECKTOR Challenge Missing values are encoded b...
9945957
from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: __version__ = 'undefined' try: import OpenGL # noqa except ImportError: raise ImportError("The PyOpenGL package is required for this plugin") else: d...
9945968
from pydantic import Field from sirena_client.base.models.base_client_request import RequestModelABC class UnArchiveOrder(RequestModelABC): rloc: str = Field(description="Номер бронирования") lang: str = 'en' _method_name: str = 'unarchive_pnr' def build(self) -> dict: request = { ...
9945997
from .instance_segmentation_security.instance_segmentation_security_0010 import InstanceSegmentation0010 from .instance_segmentation_security.instance_segmentation_security_1025 import InstanceSegmentation1025 __model_factory = { 'instance_segmentation_0010': InstanceSegmentation0010, 'instance_segmentation_1...
9946024
import ee import time import json import requests import numpy as np import pandas as pd import xarray as xr from tqdm import tqdm from io import BytesIO from pyproj import CRS from pathlib import Path from collections.abc import Iterable from concurrent.futures import ThreadPoolExecutor from restee.core import Domain...
9946045
class Solution(object): count = 0 def totalNQueens(self, n): """ :type n: int :rtype: int """ self.count = 0 cols = [] self.helper(n, cols) return self.count def helper(self, n, cols): if len(cols) == n: self.count += 1 ...
9946115
from client import APIManager realKey = "<KEY>" notRealKey = "<KEY>" apiMgr = APIManager.APIManager("https://api.sneakercopter.io") # Will be valid print("Checking key: %s" % realKey) validity = apiMgr.verifyKey(realKey) print("Authentication success: %s" % validity) # Will be invalid print("Checking key: %s" % ...
9946200
import FWCore.ParameterSet.Config as cms from CalibMuon.Configuration.getCSCConditions_frontier_cff import *
9946213
import logging,os,cPickle,time from statbin import statbin from random import choice, random, sample import numpy as np import networks class D2QN: def __init__(self, env, nframes=1, epsilon=0.1, discount=0.99, train=1, update_nsamp=1000, timesteps_per_batch=1000, dropout=0, batch_size=32, nfit_epoch=1, epsilon_s...
9946225
import unittest from postpy import uuids class TestUUIDFunctions(unittest.TestCase): def test_function_formatters(self): expected = 'gen_random_uuid()' result = uuids.random_uuid_function() self.assertEqual(expected, result) expected = 'my_schema.uuid_generate_v1mc()' ...
9946232
import unittest from mpesa.api.b2c import B2C class B2CTests(unittest.TestCase): def setUp(self): self.mpesa_b2c_object = B2C("sandbox", app_key="<KEY>", app_secret="<KEY>", sandbox_url="https://san...
9946244
from clockwork import read_trim def run(options): assert len(options.reads_files) % 2 == 0 for i in range(0, len(options.reads_files), 2): out1 = options.outprefix + "." + str(int(i / 2)) + ".1.fq" out2 = options.outprefix + "." + str(int(i / 2)) + ".2.fq" read_trim.run_trimmomatic( ...
9946253
from django.test import TestCase from .test_app.models import Post from fast_drf.utils.enums import HTTPVerbsEnum class FastDRFTestCase(TestCase): def setUp(self): self.model = Post api_config = { 'api_url': 'posts', 'allowed_methods': [HTTPVerbsEnum.GET.value, HTTPVerbsEn...
9946256
import numpy as np import torch.nn as nn import torch.nn.functional as F import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class SigmaLoss: def __init__(self, N_samples, perturb, raw_noise_std): super(SigmaLoss, self).__init__() self.N_samples = N_samples s...
9946259
import sys import time import io import csv # Imports for inferencing import cv2 import onnxruntime as rt from inference import run_onnx import numpy as np # Imports for communication w/IOT Hub from azure.iot.device import IoTHubDeviceClient from azure.iot.device import Message from azure.core.exceptions import Resou...
9946260
import csv import datetime from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseForbidden from intake.models import FormSubmission @login_required def email_csv(request): if not request.user.has_perm('clips.change_clip'): return HttpResponseForbidden...
9946263
import pygame from screens.screen import Screen class CreditsScreen(Screen): def __init__(self, display) : super().__init__(display=display) self.texture = self.tex_manager.get_texture("credits_screen")
9946270
import unittest as ut from lxml.etree import XMLPullParser from taky.util import XMLDeclStrip class XDCTest(ut.TestCase): def setUp(self): parser = XMLPullParser(tag="event") parser.feed(b"<root>") self.xdc = XMLDeclStrip(parser) def test_valid_xml(self): self.xdc.feed(b"<?x...
9946281
import json import time import traceback from inspect import isclass, isfunction from typing import Callable, Union import pretty_errors from devtools import debug, pprint from sanic import Sanic # from sanic.websocket import WebSocketProtocol from pepperbot.action.chain import * from pepperbot.command.handle import h...
9946298
import click import urlparse from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @click.command() @click.argument('base_url', type=str) def main(base_url): if not base_ur...
9946317
from .telenium_process import TeleniumTestProcess from .common import skip_screen_checks from .common import ordered test_address = { 'invalid_address': '<KEY>', 'autoresponder_address': '<KEY>', 'recipient': '<KEY>', 'sender': '<KEY>' } class AddressBook(TeleniumTestProcess): """AddressBook Scre...
9946321
from examples.things import app import falcon.testing as testing def test_things_resource_response(): client = testing.TestClient(app) resp = client.simulate_get('/things') assert resp.status_code == 200 assert resp.text == ( '\nTwo things awe me most, the starry sky above me and the moral l...
9946373
from __future__ import division import sys import os from classify import Classify from db import Db classifier = Classify() def is_doctype_valid(doctype): return Db().get_words_count(doctype) > 0 def check_file(f): results = [] for line in open(f, 'r').readlines(): try: classifier.set_text(line) results ...
9946395
import numpy as np import pandas as pd # TODO: look into providing indexing for TimeBase class TimeBase(object): """ Basic container for a single timeseries made up of key/value pairs. Implementation note: this class is required by TimeArray due to pandas.ExtensionArray's need for a base object (i.e....
9946449
from .constant_prob_sampler import ConstantProbSampler # NOQA from .crp_sampler import CRPSampler # NOQA from .fewshot_sampler import FewshotSampler # NOQA from .hierarchical_episode_sampler import HierarchicalEpisodeSampler # NOQA from .incremental_sampler import IncrementalSampler # NOQA from .minibatch_sampler ...
9946466
import sys from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QApplication, QAction, qApp, QTextEdit, QLabel, QHBoxLayout, QVBoxLayout, QLineEdit, QGridLayout from PyQt5.QtGui import QFont, QIcon class main(QMainWindow): def __init__(self): super().__init__() self.initUI() def init...
9946498
class Solution: def letterCasePermutation(self, S: str) -> List[str]: count = sum(c.isalpha() for c in S) result = [] for i in range(1 << count): b = 0 curr = [] for c in S: if c.isdigit(): curr.append(c) ...
9946502
import sys from collections import defaultdict output_filename_prefix=sys.argv[1][:-2] input_filenames=sys.argv[2:] output_filename_en=output_filename_prefix+"en" en_vocab=defaultdict(int) unl=u"\n" for filename in input_filenames: print >>sys.stderr, "FILE: "+filename output_filename=output_filename_prefix+fil...
9946513
import sys import os import logging import wakeonlan sys.path.append('../') from samsungtvws import SamsungTVWS # Increase debug level logging.basicConfig(level=logging.INFO) # Normal constructor tv = SamsungTVWS('192.168.xxx.xxx') # Autosave token to file token_file = os.path.dirname(os.path.realpath(__file__)) ...
9946520
import logging import sys from rasterio.rio.main import main_group logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) def test_sample_err(runner): result = runner.invoke( main_group, ['sample', 'bogus.tif'], "[220650.0, 2719200.0]") assert result.exit_code == 1 def test_s...
9946540
tables_sql = "SELECT table_schema || '.' || table_name "\ "FROM information_schema.tables "\ "WHERE table_type = 'BASE TABLE' "\ "AND table_schema NOT IN ('pg_catalog', 'information_schema');" all_projects_sql = """select distinct p.project_name ,array_agg(dis...
9946549
from airflow import DAG from datetime import datetime, timedelta from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator from airflow.operators.dummy_operator import DummyOperator from airflow_utils import pod_env_vars, DBT_IMAGE default_args = { "owner": "airflow", "depends_on_pa...
9946556
import gdown import re import cv2 import numpy as np import webcolors import matplotlib import matplotlib.pyplot as plt from modules.detection import draw_bbox def download_weights(id_or_url, cached=None, md5=None, quiet=False): if id_or_url.startswith('http'): url = id_or_url else: url = 'https...