content
stringlengths
5
1.05M
''' Application-wide preferences. ''' from transformers import RobertaTokenizerFast import spacy from . import TOKENIZER_PATH class Config: vocab_size = 54_000 max_length = 512 # tokens! min_char_length = 120 # characters split_ratio = { 'train': 0.7, 'eval': 0.2, 'test': 0.1...
#!/usr/bin/env python3 """ A program to filter tweets that contain links to a web archive. At the moment it supports archive.org and archive.is, but please add more if you want! """ import json import fileinput archives = ["archive.is", "web.archive.org", "wayback.archive.org"] for line in fileinput.input(): tw...
import numpy as np import math def upper_error(x, f, neg=False): n = len(x) p = np.linspace(np.min(x), np.max(x)) max_fun = 0 max_prod = 0 for val in p: fun = 0 if neg: fun = abs(-f(val)) else: fun = abs(f(val)) if fun > max_fun: ...
_ANDROID_CPUS_TO_PLATFORMS = { "arm64-v8a": "@io_bazel_rules_go//go/toolchain:android_arm64_cgo", "armeabi-v7a": "@io_bazel_rules_go//go/toolchain:android_arm_cgo", "x86": "@io_bazel_rules_go//go/toolchain:android_386_cgo", "x86_64": "@io_bazel_rules_go//go/toolchain:android_amd64_cgo", } _IOS_CPUS_TO_...
""" MozTrap root URLconf. """ from django.conf.urls import patterns, url, include from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from moztrap.model import mtadmin admin.site = mtadmin.MTAdminSite() admin.autodiscover() import session_csrf session_csrf...
from hlt import * from networking import * myID, gameMap = getInit() sendInit("BasicPythonBot") while True: moves = [] gameMap = getFrame() for y in range(gameMap.height): for x in range(gameMap.width): site = gameMap.getSite(Location(x, y)) if site.owner == myID: ...
import origami_rectangle as rect import scadnano as sc def create_design(): design = rect.create(num_helices=16, num_cols=28, seam_left_column=12, assign_seq=False, num_flanking_columns=2, num_flanking_helices=2, edge_staples=False, scaffo...
import numpy as np import pdb from tensorflow import flags from copy import deepcopy FLAGS = flags.FLAGS def euclidean_proj_simplex(v, s=1): assert s > 0, "Radius s must be strictly positive (%d <= 0)" % s n, = v.shape # will raise ValueError if v is not 1-D # check if we are already on the simplex ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re from setuptools import find_packages, setup def get_version(package): """ Return package version as listed in `__version__` in `init.py`. """ with open(os.path.join(package, "__init__.py")) as f: return re.search("__version__ ...
file_to_work = open("noman.txt", "r") content = file_to_work.read() print(content) file_to_work.close() print("\n\n\n\n\n") file_to_work = open("noman.txt", "r") just_one_character = file_to_work.read(1) print(just_one_character) remaining_four_characters = file_to_work.read(4) print(remaining_four_characters) re...
from abc import ABC from ...batch.lazy.lazy_evaluation import PipeLazyEvaluationConsumer, LazyEvaluation from ...common.types.bases.j_obj_wrapper import JavaObjectWrapper from ...common.types.conversion.type_converters import j_value_to_py_value from ...common.utils.printing import print_with_title from ...py4j_util i...
alex_salon = ['Audi R8 e tron', 'Mercedes Benz gle 400', 'Tesla Model S'] oleg_salon = ['Лада Калина', 'Запорожець'] len_alex_salon = len(alex_salon) len_oleg_salon = len(oleg_salon) if len_alex_salon < len_oleg_salon: print("У Олега машин більше") else: print("В Алексія машин більше")
#! /usr/bin/env python """ ------------------------------------------------------------------------------------------------------------------------ ____ __ __ __ __ __ / __ \__ __/ /_/ /_ ____ ____ / / / /__ ____ _____/ /__ _____ ...
#!/usr/bin/env python ''' Created on 25 Apr 2021 This file contains functions to get coordinates for animations of lightcones in causal sets. @author: Christoph Minz @license: BSD 3-Clause ''' from __future__ import annotations from typing import List, Tuple import numpy as np from math import sqrt d...
""" Tests for hashtag. """ import responses def test_get_info(helpers, api): hashtag_id = "17843826142012701" with responses.RequestsMock() as m: m.add( method=responses.GET, url=f"https://graph.facebook.com/{api.version}/{hashtag_id}", json=helpers.load_json(...
"""oauth 1.0 flow for khan-api""" from __future__ import print_function, unicode_literals import requests_oauthlib import requests import urlparse import webbrowser from six.moves import input # package specific import pkaaw.constants def get_request_tokens(consumer_key, consumer_secret): """uses request_oauthlib...
from multiprocessing import Process, Queue, Array import ctypes import sys import os import mappy as mp import numpy as np import pysam from datetime import datetime from datetime import date from . import version def load_manifest(path, preset): manifest = { "preset": preset, "references": [ ...
"""Tests for the Dirac distributions.""" import unittest import numpy as np from probnum import random_variables as rvs class TestDirac(unittest.TestCase): """General test case for the Dirac distributions.""" def setUp(self): self.supports = [1, np.array([1, 2]), np.array([[0]]), np.array([[6], [-0...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/dataclassUtil.ipynb (unless otherwise specified). __all__ = ['enforce_types'] # Cell import inspect import typing from contextlib import suppress from functools import wraps # Cell def enforce_types(callable): spec = inspect.getfullargspec(callable) def check_...
from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db import models from django.utils.translation import ugettext_lazy as _ from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import...
from django.db import models from django.contrib.auth.models import User class Client(models.Model): name = models.CharField(max_length=100, unique=True) account = models.CharField(max_length=20, unique=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.Date...
""" # Author Jakob Krzyston (jakobk@gatech.edu) # Purpose Build architecture for I/Q modulation classification as seen in Krzyston et al. 2020 """ import torch from torch import nn from torch import optim import torch.nn.functional as F ##### LINEAR COMBINATION FOR COMPLEX CONVOLUTION ##### class LC(nn.Module): ...
#Main Sedov Code Module #Ported to python from fortran code written by James R Kamm and F X Timmes #Original Paper and code found at http://cococubed.asu.edu/papers/la-ur-07-2849.pdf import numpy as np from globalvars import comvars as gv from sedov_1d import sed_1d from matplotlib import pyplot as plt gv.its = 10 #...
# Generated by Django 2.0.4 on 2018-04-04 23:37 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assignments', '0006_auto_20180404_2334'), ] operations = [ migrations.AlterField( model_name='assig...
from typing import Dict, List, Optional, Tuple, Union import torch from torch_geometric.nn import (GlobalAttention, Set2Set, global_add_pool, global_max_pool, global_mean_pool) from torch_geometric.utils import softmax from torch_scatter import scatter_add class MaxReadOut(torch.nn.Mo...
import pandas as pd from header_list import rename_list, match_list import time def main(filename): """Cleans up the CSV file Takes the CSV file and puts it into a pandas dataframe then cleans it up to make it easier to upload into the RG bulk import tool. Args: filename::pan...
# -*- encoding: utf-8 -*- # # Copyright © 2013 eNovance <licensing@enovance.com> # # Authors: Mehdi Abaakouk <mehdi.abaakouk@enovance.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # ...
from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django import forms from django.utils.regex_helper import Choice from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries...
# from django.contrib.admin.views.decorators import staff_member_required from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.http import Http404 from django.http.request import split_domain_port from django.shortcuts...
#!/usr/bin/env python # -*- coding: utf-8 -*- """\ This script creates a triplet sparse matrix """ import diypy3 d = diypy3.Diypy3() d.triplet_sparse_matrix((1, 1, 'hello'), (2, 1, 'how'), (1, 2, 'are'), (2, 2, 'you'))
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Download and build the data if it does not exist. import json import os from parlai.core import build_data from parla...
import click from ghutil.types import Release @click.command() @click.option('-f', '--force', is_flag=True, help='Delete without prompting') @Release.argument('release', implicit=False) @click.argument('asset') def cli(release, asset, force): """ Delete a release asset """ s = release.asset(asset) if for...
# Copyright (c) 2018 Turysaz <turysaz@posteo.org> import pygame from .ConfigurationService import create_configuration_parser from .EventAggregator import EventAggregator from .IoCContainer import IoCContainer from .MainControl import MainControl from .MainView import MainView from .ObjectFactory import ObjectFactory...
# Question 6 Lab 03 # AB Satyaprakash (180123062) # imports ---------------------------------------------------------------------- from math import factorial from fractions import Fraction import numpy as np import sympy as sp # ------------------------------------------------------------------------------ # functions...
from . import file_hdf4, file_hdf5, file_idl, file_netcdf
import warnings import re import py import pytest from _pytest.recwarn import WarningsRecorder def test_recwarn_functional(testdir): reprec = testdir.inline_runsource(""" import warnings oldwarn = warnings.showwarning def test_method(recwarn): assert warnings.showwarning != old...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os import subprocess import fnmatch import xml.etree.ElementTree as ET import string def get_user_plist_filenames(): files = [] for filename in os.listdir(basepath): if fnmatch.fnmatch(filename, '[!_|!nobody]*.plist'): files.append(fil...
from flask import Flask, request from bot import Bot import os TOKEN = os.environ.get('VK_TOKEN') confirmation_code = os.environ.get('VK_CONF') SECRET = os.environ.get('VK_SECRET') server = Flask(__name__) bot = Bot(token=TOKEN) last_msg = None @server.route('/'+SECRET, methods=['POST']) def handle(): data = re...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
from datasets.data_utils.Crawlers import BaiduPic class WebCrawler: @staticmethod def goToFind(keys, limit=8000): baidu_list = BaiduPic.goToFind(keys, limit)
# -*- coding: utf-8 -*- """ {{cookiecutter.package_name}}.config {{(cookiecutter.package_name + ".config") | length * '~'}} Application configurations. """ import os #pylint: disable=too-few-public-methods class Config(object): """Application's base configuration.""" APP_PATH = os.path.abspath(...
class InvalidAuthorizationToken(RuntimeError): pass class NoTeamsError(RuntimeError): pass class MultipleTeamsError(RuntimeError): def __init__(self, teams): self.teams = teams class CommandError(RuntimeError): pass class DataEntryError(ValueError): pass class ConfigurationError(Ru...
__all__ = [ 'interfaces', 'pipelines', 'utils', 'wfmaker' '__version__' ] from .pipelines import Couple_Preproc_Pipeline, TV_Preproc_Pipeline from .wfmaker import wfmaker from .version import __version__
#!/usr/bin/env python r""" >>> Pattern('/{a}').parse('/foo.html') PatternResult(a='foo.html') >>> Pattern('/{a}.html').parse('/foo.html') PatternResult(a='foo') Each substitution pattern tries to consume as much as possible by default >>> Pattern('/{a}').parse('/a/b/c') PatternResult(a='a/b/c') Override the ``def...
# -*- coding: utf-8 -*- """ Created on Sun Apr 12 22:46:16 2020 @author: chens """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from pathlib import Path from geoist.pfm import normgra from geoist import DATA_PATH # 1.读取数据 datapath = Path(Path(normgra.__file__).parent, 'data') filename = Pat...
#!/usr/bin/python ## "non-linear barotropically unstable shallow water test case" ## example provided by Jeffrey Whitaker ## https://gist.github.com/jswhit/3845307 ## ## Running the script should pop up a window with this image: ## http://i.imgur.com/ZlxR1.png import numpy as np import shtns class Spharmt(object): ...
import argparse import editdistance import numpy as np import os import sys import multiprocessing as mp import subprocess parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_path', type=str, help='This should point to the folder that contains your demultiplexed R2C2 fasta and subread (ending on _sub...
#!/usr/bin/env python2 """ Client for Project 2 """ import socket import sys __author__ = 'Matthew Wang and Tony Tan' __copyright__ = "Copyright 2019, Matthew Wang and Tony Tan" __license__ = "MIT" __version__ = "1.0" def arg_check(): """ Parses and verifies command line arguments. :return: none ""...
# -*- coding: utf-8 -*- """ Common handlers for ibpy Created on Thu Mar 19 22:34:20 2015 @author: Jev Kuznetsov License: BSD """ import pandas as pd from ib.ext.Order import Order class Logger(object): """ class for logging and displaying icoming messages """ def __init__(self,tws): tws.registerAll...
#!/usr/bin/python3 import logging.handlers import sys import signal import time import traceback import discord_logging import praw_wrapper import argparse from praw_wrapper import PushshiftType log = discord_logging.init_logging( backup_count=20 ) import counters from database import Database import static import...
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS SOFTWARE IS PR...
from bottle import request, redirect def authenticate(func): def wrapper(*args, **kwargs): authenticated = True session = request.environ.get('beaker.session') if not session.get('Logged-In') or not session['Logged-In']: authenticated = False session['Logged-In'] = ...
# terrascript/rundeck/__init__.py import terrascript class rundeck(terrascript.Provider): pass
import requests from typing import Dict, List class LIFX: ''' docs: https://api.developer.lifx.com selectors: https://api.developer.lifx.com/docs/selectors ''' url = 'https://api.lifx.com' def __init__(self, token): self.headers = { 'Authorization': f'Bearer {token...
from django.apps import AppConfig class TmmConfig(AppConfig): name = 'tmm'
import sys, requests, fire, json, xml server = "https://rest.ensembl.org" exp_message = "\nExport output?\nIf Yes, it will overwrite output.(json/xml)\nY or N\n" json_search_message = "Do you want to search in the json?\nY or N\n" def GET_tax_id(id, format): """ Search for a taxonomic term by its identifier o...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 7 10:31:29 2020 @author: twguest """ ############################################################################### import sys sys.path.append("/opt/WPG/") # LOCAL PATH sys.path.append("/gpfs/exfel/data/user/guestt/WPG") # DESY MAXWELL PATH sys...
import asyncio import aiohttp import aiozipkin as az from aiohttp import web page = """ <html lang="en"> <head> <title>aiohttp producer consumer demo</title> </head> <body> <h1>Your click event send to consumer</h1> </body> </html> """ backend_service = 'http://127.0.0.1:9011/consume' async def index(req...
from adventurelib_with_characters import * """ adventure specific settings """ """define the items available and where to find them""" Room.items = Bag() axe = Item('an axe', 'axe') key = Item('a key', 'key') letter = Item('a letter from Dàin', 'letter') moonstone = Item('a moonstone', 'moonstone') runepaper = Item...
# main.py # Author: Richard Gibson # # Launch point for the app. Defines all of the URL handles, including a # default handler for all non-matching URLs. # import webapp2 import front import signup import login import logout import submit import presubmit import runnerpage import gamepage import handler import gameli...
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models class SingleGFK(models.Model): """ An abstract base model to simplify the creation of models with a GFK'd "object" relationship. """ object_type = models.Foreign...
""" Calculates PSNR for JPG with respect to a dataset. Note: Currently hard-coded for Cifar10 """ import sys import os sys.path.append(os.path.abspath('..')) import argparse import numpy as np import torch import cv2 from collections import namedtuple from PIL import Image from tqdm import tqdm from utils import util_...
# Copyright 2021 Pants project contributors. # Licensed under the Apache License, Version 2.0 (see LICENSE). from datetime import time from django.http import Http404, HttpResponse from helloworld.greet.models import Greeting def index(request, slug): try: greeting = Greeting.objects.get(slug=slug) ...
import sqlite3 import pendulum import psycopg2 class SqliteDatabase: def __init__(self, host, db, user, pw): self.host = host self.db = db self.user = user self.pw = pw self.create() def connect(self): return psycopg2.connect(host=self.host,database=self.db, use...
"""See README.md for package information.""" __version__ = '0.6.0' if "bpy" in locals(): import importlib importlib.reload(cli) importlib.reload(client) importlib.reload(parser) importlib.reload(server) importlib.reload(stats) else: from . import cli from . import client from . imp...
''' Write and read csv file ''' import csv def write_to_csv(v): offset = 0 size = len(v) lines = 50 with open('data.csv', 'w') as f: csvout = csv.writer(f) csvout.writerows(v) def read_from_csv(): with open('data.csv', 'r') as f: csvin = csv.reader(f) for row in csv...
""" Construct a FeatureExtraction class to retrieve 'key points', 'partitions', `saliency map' of an image in a black-box or grey-box pattern. Author: Min Wu Email: min.wu@cs.ox.ac.uk """ import copy import numpy as np import cv2 import random from scipy.stats import norm from keras import backend as K from matplotli...
print(''' so this is a simple milti-line print ================= | | | | | Box | | | | | ================= ''')
from category.models import Category from django.db.models import Q from django.utils import timezone from profile.models import UserProfile from rest_framework.generics import get_object_or_404 from rest_framework.pagination import PageNumberPagination from rest_framework.request import Request from .models import Ev...
from datetime import date, datetime import robin_stocks.robinhood as r from pyrh import Robinhood import pandas as pd import csv from collections import Counter from robin_stocks.robinhood.export import export_completed_option_orders import xlsxwriter as xl from jproperties import Properties def getCredentials(): ...
# ============================================================================= # Imports # ============================================================================= import seaborn as sns from main import main import numpy as np import matplotlib.pyplot as plt import random import math import sys import p...
from __future__ import print_function from builtins import range import numpy as np from sklearn.base import BaseEstimator, clone from sklearn.utils.validation import check_X_y, check_array, check_is_fitted # from scipy.spatial.distance import cdist from sklearn.metrics.pairwise import pairwise_distances as cdist from...
from functools import partial import itertools import numpy as np from rlkit.core.distribution import DictDistribution from rlkit.samplers.data_collector.contextual_path_collector import ( ContextualPathCollector ) from rlkit.envs.contextual import ContextualRewardFn from gym.spaces import Box from rlkit.sampler...
#!/usr/local/miniconda2/bin/python # _*_ coding: utf-8 _*_ """ python train_word2vec_model.py wiki.en.text(语料库) word2vec_wiki.en.text.model word2vec_wiki.en.text.vector 得到了一个gensim中默认格式的word2vec model和一个原始c版本word2vec的vector格式的模型: wiki.en.text.vector @author: MarkLiu @time : 17-8-30 下午4:46 """ from __future__ import ...
from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic import DetailView, CreateView # from django.contrib.auth.forms import ( # UserCreationForm, # UserChangeForm, # PasswordChangeForm, # ) from django.contrib.auth.views import PasswordChangeView f...
# Maciej Izydorek # prints out a random fruit import random # lists of fruits fruits = ('apple', 'banana', 'kiwi', 'orange', 'grapefruit', 'raspberry') # random number starting at 0 up to length of list - 1 to do not get out of the list index random = fruits[random.randint(0,len(fruits)-1)] print('A random fruit: {}'...
from setuptools import setup s_args = { 'name': 'eqclustering', 'version': '0.1.0', 'description': 'Statistical earthquake clustering algorithm', 'author': 'Mark Williams', 'maintainer': 'Nevada Seismological Laboratory', 'maintainer_email': 'nvseismolab@gmail.com', 'url': 'https//github.co...
import ast import inspect from .handler import handle def compile(func): import os import tempfile fname = tempfile.NamedTemporaryFile(delete=False, suffix='.c') out = tempfile.NamedTemporaryFile(delete=False, suffix='.out') source = transpile(func) with open(fname.name, 'w') as f: ...
from ezweb.objects.soup import EzSoup from ezweb.objects.source import EzSource from ezweb.objects.product import EzProduct
#!/usr/bin/env python '''Farmware Tools: Device.''' from __future__ import print_function import os import sys import uuid from functools import wraps import requests from ._util import _request_write, _response_read, _mqtt_request, _mqtt_status from .auxiliary import Color from .env import Env COLOR = Color() ENV =...
# !/usr/bin/python """ Author: Thomas Laurenson Email: thomas@thomaslaurenson.com Website: thomaslaurenson.com Date: 2016/02/23 Description: printTimeTaken.py prints processing time of RegXML generated by CellXML-Registry. Copyright (c) 2016, Thomas Laurenson """ import os import sys import glob ############...
class demomethod: x = 0 y = 0 z = [] @staticmethod #静态方法的装饰器 def static_mthd(): #define the static method print("static method") @classmethod #类方法的装饰器 def class_mthd(cls): #define the class method print("class met...
import csv import random import cv2 import numpy as np import os from tensorflow.keras.preprocessing.image import load_img from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import ImageDataGenerator def load_data(paths, undersamples = [], set = 'train'): ""...
from io import StringIO from collections import defaultdict import logging from typing import Dict, List from ror.RORModel import RORModel from ror.RORParameters import RORParameters from ror.RORResult import RORResult from ror.ResultAggregator import AbstractResultAggregator from ror.alpha import AlphaValue, AlphaValu...
# Copyright Epic Games, Inc. All Rights Reserved. import time from . import utilities from ..dependencies import remote_execution unreal_response = '' def run_unreal_python_commands(remote_exec, commands, failed_connection_attempts=0): """ This function finds the open unreal editor with remote connection en...
# --- Day 2: Password Philosophy --- # Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan. # The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a...
import torch import torch.nn as nn import numpy as np import math import yaml from ..utils.config import cfg from ..rpn.generate_anchors import generate_anchors from ..utils.bbox import bbox_transform_inv ,clip_boxes, clip_boxes_batch from ..nms.nms_wrapper import nms import pdb DEBUG = False class _Proposallayer(...
# pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from datetime import time import numpy as np import pytz from candystore import CandyStore from tests.helpers import ColumnAssertionMixin from augury.pipelines.betting import...
''' Description: Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtr...
""" https://blog.csdn.net/freeking101/article/details/64461574 """ import pathlib from xml.etree import cElementTree as ET PATH = pathlib.Path(__file__).parent.absolute() INPUT = PATH / "RSS.xml" has_img = PATH / "has_img.txt" not_has_img = PATH / "not_has_img.txt" tree = ET.ElementTree(file=INPUT) root = tree.getro...
""" Dane są ciągi: A[n+1] = sqrt(A[n] ∗ B[n]) oraz B[n+1] = (A[n] + B[n])/2.0. Ciągi te są zbieżne do wspólnej granicy nazywanej średnią arytmetyczno-geometryczną. Napisać program wyznaczający średnią arytmetyczno-geometryczną dwóch liczb. """ from math import sqrt a0 = int(input("Enter a0: ")) b0 = int(input("Enter b...
from abc import ABC, abstractmethod import json from enum import Enum import numpy as np import tensorflow as tf class TensorflowObjectDetector: def __init__(self, model_path, category_labels_path): """ :param model_path: string location of serialized frozen model :param category_labels_p...
import EulerRunner def problem3_iter(): to_factor = 600851475143 gen = EulerRunner.prime_generator() current_prime = None while to_factor > 1: current_prime = gen.next() while to_factor % current_prime == 0: to_factor /= current_prime return current_prime EulerRunner....
from django.db import migrations def initial_models(apps, *args): """ An initial data migration to create the necessary account related models. """ # Need at least one account tier for accounts to belong to AccountTier = apps.get_model("accounts", "AccountTier") one = AccountTier.objects.crea...
import re from config import Config, BankDict, Wealth, Logger import os from utils.nlp_util import transfer_to_yuan from utils.nlp_util import UTIL_CN_NUM class ManualText(object): # 从PDF等文件的文字内容中,提取符合正则表达式的内容,来补充之前在表格中提取的,然而未能提取到的内容 log_path = os.path.join(Config.LOG_DIR, 'ManualText.log') log ...
def read_csv_data(file_name, skip=1, samples=120, sep=','): data = [] with open(file_name) as csv_file: first = csv_file.readline() if len(first) == 0: return data rows = 1 cols = len(first.split(sep)) while csv_file.readline(): rows += 1 data...
from __future__ import division, absolute_import, print_function from beets.dbcore import FieldQuery from beets.plugins import BeetsPlugin # Copied from beets.dbcore with two additions of 'not' class NotNoneQuery(FieldQuery): """A query that checks whether a field is not null.""" def col_clause(self): ...
class Config: is_new_version: bool = False is_c611: bool = True # 金制空气c611 or ds-air b611
#!/usr/bin/env python3 import os import gzip import re from collections import defaultdict from pathlib import Path # set variables from snakemake params, wildcards, input and threads ROOT = str(snakemake.wildcards.root) MASKS = snakemake.params.mask_ids + [32630,111789,6] # mask synthetic constructs by default NODES...
# ------------------------------------------------------------------------------------------------ # Given a list of numbers and a number k, return whether any two numbers from the list add up to k # # ------------------------------------------------------------------------------------------------ def find_k(l, k): ...