text
stringlengths
2
999k
import os import string import random import hashlib import subprocess import time import json import secrets from models import db_session from models.users import User from models.tests import Test from models.forums import Forum db_session.global_init('database.db') def hash_password(password): h = hashlib.md5(p...
from django.db import models # Wehaa Portal from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from django.utils import timezone from taggit.managers import TaggableManager from tinymce.models import HTMLField from core.utils import count_words, read_ti...
import os import sys import argparse import _pickle as pickle import json import cv2 import numpy as np from sklearn.cluster import KMeans class DenseDetector(): def __init__(self, step_size=20, feature_scale=20, img_bound=20): # Create a dense feature detector self.initXyStep = step_...
# from bitarray import bitarray # import random import math import statistics # import copy import numpy as np # import logging import collections from numpy import linalg as LA def get_covariance_matrix(data): arr = np.array(data) return np.cov(arr, bias=False) # return np.cov(arr, bias=True) # covMat...
import numpy as np import skimage.measure import skimage import pandas from scipy.spatial import Delaunay from scipy.spatial import Voronoi from sklearn.decomposition import PCA from tqdm import tqdm # IMPORTANT CONVENTIONS: Following standard practice, # all images hvae shapes Z, X, Y, C where C in the # fluo channel...
#coding:utf-8 from django.contrib import admin from blog.models import Article,Category,Carousel,Nav,Column,News import markdown admin.site.site_header = '樊樊家园后花园' admin.site.site_title = '樊樊家园后台管理系统' class CategoryAdmin(admin.ModelAdmin): search_fields = ('name',) list_filter = ('status','create_time') l...
# -*- coding: utf-8 -*- # Copyright 2012 Loris Corazza, Sakis Christakidis # # 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 # # U...
from semantics.tools import conforms, join, join_list, smart_add import semantics.visitor as visitor from semantics.tools import Context, ErrorType, Scope, SelfType, SemanticError, TypeBag from parsing.ast import ArithmeticNode, AssignNode, AttrDeclarationNode, BlocksNode, BooleanNode, CaseNode, CaseOptionNode, ClassDe...
import os import numpy as np import pandas as pd import multiprocessing as mp from keras import backend as K from keras.preprocessing.image import (ImageDataGenerator as _ImageDataGenerator, DirectoryIterator as _DirectoryIterator, Iterator ...
""" Checks that the functional test program (functest) can be successfully built and executed for every scheme/implementation. """ import os import platform import unittest import pytest import helpers import pqclean @pytest.mark.parametrize( 'implementation,test_dir,impl_path, init, destr', [(impl, *helpe...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'bot_update', 'gclient', 'gerrit', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'achristos.settings') try: from django.core.management import execute_from_command_line except Im...
"""Support for deCONZ lights.""" from pydeconz.light import Light from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, DOMAIN, EFFECT_COLORLOOP, FLASH_LONG, FLASH_SHORT, SUPPORT_BRIGHTNESS, ...
# Copyright The IETF Trust 2010-2020, All Rights Reserved # -*- coding: utf-8 -*- # changing state and metadata on Internet Drafts import datetime import os import glob import shutil from django import forms from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators imp...
class Solution(object): # O(n) def jump(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <= 1: return 0 # treat 0 as 1, since test work as nums = [max(1, e) for e in nums] i = 0 jump = 1 #...
from flask import Flask from flask import render_template from flask import request from flask import jsonify from flask import send_file from flask import redirect from flask import url_for import json import os import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import torc...
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정 import numpy as np from collections import OrderedDict from common.layers import * from common.gradient import numerical_gradient class MultiLayerNetExtend: """완전 연결 다층 신경망(확장판) 가중치 감소, 드롭아웃, 배치 정규화 구현 Parameters ---...
# Copyright 2021 RelationalAI, Inc. # # 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 # # Unless required by applicable law or agreed to in wr...
# -*- coding:utf-8 -*- # /usr/bin/env python """ Date: 2020/3/17 22:11 Desc: world bank interface """ import collections import datetime import re import warnings import pandas as pd import tabulate from decorator import decorator from . import fetcher BASE_URL = "https://api.worldbank.org/v2" COUNTRIES_URL = f"{BAS...
""" Formtools Preview application. """ import cPickle as pickle from django.conf import settings from django.http import Http404 from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils.hashcompat import md5_constructor from django.utils.crypto im...
import matplotlib as mpl from . import _path as mypath from ._text import _get_arrow_style def draw_patch(data, obj): """Return the PGFPlots code for patches. """ if isinstance(obj, mpl.patches.FancyArrowPatch): data, draw_options = mypath.get_draw_options( data, obj, ...
# -*- coding: utf-8 -*- import json from django.test import TestCase from blueking.component import collections from blueking.component.client import BaseComponentClient, ComponentClientWithSignature from blueking.tests.utils.utils import tests_settings as TS # noqa class TestBaseComponentClient(TestCase): @cl...
from threading import Lock from six import with_metaclass from ploceidae.utilities.singleton_implementer import SingletonImplementer from ploceidae.dependency.garbage_collection.scheduler import Scheduler class GarbageCollectionObserver(with_metaclass(SingletonImplementer)): """ Handles freeing of dependenci...
# coding: utf-8 from decimal import Decimal from typing import Dict, Optional, Tuple import lxml.etree import raven import core.network from core.utils import Currency, ILogger, DictUtils class CentralBankApiClient(object): __CURRENCY_CODES = { Currency.EUR: 'EUR', Currency.RUR: 'RUR', ...
"""Test the Logitech Harmony Hub remote.""" from datetime import timedelta from aioharmony.const import SendCommandDevice from openpeerpower.components.harmony.const import ( DOMAIN, SERVICE_CHANGE_CHANNEL, SERVICE_SYNC, ) from openpeerpower.components.harmony.remote import ATTR_CHANNEL, ATTR_DELAY_SECS ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Contains unit tests for functionality related to retrieving keys. import os import pytest import unittest from tempfile import TemporaryDirectory from unittest.mock import patch from djangokeys.deprecated.retrieve import retrieve_key_from_file from djangokeys.setting...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re, operator from acdef import acdef from formatter import formatter from issue import Issue from utils.defvars import builtins from lexer import tokenizer, LINESTARTS from validation import vsetting, vvariable, vstring, vsetting_aval # C_LF = 'f' # C_LT = 't' #...
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 14:56:02 2019 @author: HankTown """ from trasso import extract asso_result=extract.get_asso_words('rdbg2019.txt','stopwords.txt','习近平',m=20) for w in asso_result: print(w)
# coding=utf8 # Copyright 2018 JDCLOUD.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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
#!/usr/bin/env python # Copyright (c) 2017, the R8 project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. try: import gi from gi.repository import Notify Notify.init("R8 build tools") ...
# # PySNMP MIB module SYSLOG-MSG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYSLOG-MSG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:14:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
def palindromo(palabra): palabra = palabra.replace(' ', '') palabra = palabra.lower() palabra_invertida = palabra[::-1] if palabra == palabra_invertida: return True else: return False def run(): palabra = input("escirbe una palabra: ") es_palindromo = palindromo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .plot_manager import plot_manager from .plotter import Plotter from .plot import plot from .plot_config import PlotConfig
import unittest import requests_mock from frontstage import app from tests.integration.mocked_services import (business_party, case, categories, collection_exercise, encrypted_enrolment_code, enrolment_code, survey, token, u...
import logging from chatterbot.logic import LogicAdapter from sugaroid.brain.postprocessor import random_response from sugaroid.brain.constants import IMITATE from sugaroid.brain.ooo import Emotion from sugaroid.brain.preprocessors import normalize from sugaroid.core.statement import SugaroidStatement class Imitate...
import copy from hearthbreaker.cards.base import SpellCard, SecretCard from hearthbreaker.tags.action import Draw from hearthbreaker.tags.base import Effect, Buff, ActionTag from hearthbreaker.tags.event import Attack from hearthbreaker.tags.selector import PlayerSelector, PlayerOne, PlayerTwo, BothPlayer, Count, DeadM...
# -*- coding: utf-8 -*- """ Created on Sun Jun 13 13:51:40 2021 @author: admin """ ''' class Demo(object): total = 0 # 类数据成员 def __new__(cls, *args, **kwargs): if cls.total >= 3: # 访问数据成员 raise Exception("最多只能创建3个对象") else: return object.__new__(cl...
import numpy as np import joblib as jl import xarray as xr import pandas as pd import sys from os.path import exists from itertools import product def get_traces(sampler, nthin): """Extract traces from emcee.EnsebleSampler and apply invers transformation of parameters """ # load every nthin'th sample ...
# Python Essential Libraries by Joe Marini course example # Example file for Pendulum library import pendulum # create a datetime and print it dt1 = pendulum.datetime(2020, 7, 28, 15, 30) print(dt1) # use some formatting functions print(dt1.to_date_string()) print(dt1.to_time_string()) print(dt1.to_datetime_string())...
num=[] for cont in range(0,5): num.append(int(input(f'Informe um número para posição {cont}: '))) print(f'Os números que você digitou foram {num}') print() print(f'O maior valor digitado foi {max(num)} nas posições ', end='') for i, v in enumerate(num): if v == max(num): print(f'{i}...', end='') pri...
from time import strftime import os from .xbin import XBinIO # Can be int or float # Changes the internal type for frames indices FRAME_TYPE = float ''' ------------------- ---< NT_EXPORT >--- ------------------- ''' class Note(object): __slots__ = ('frame', 'string') def __init__(self, frame...
import pytest from unittest.mock import ANY, MagicMock, patch from os import environ import falcon from cyberdas.models import Session from cyberdas.services.mail import TransactionMail from cyberdas.config import get_cfg cfg = get_cfg() USER_EMAIL = 'haha@mail.com' FACULTY_NAME = environ['FACULTY_NAME'] REGISTERED...
import rospy import geometry_msgs.msg import numpy as np import time from nav_msgs.msg import Odometry import math #Pub Code cmd = geometry_msgs.msg.Twist() pub = rospy.Publisher('/cmd_vel', geometry_msgs.msg.Twist, queue_size=10) rospy.init_node('SQ_F', anonymous=True) rate = rospy.Rate(50) # 50hz #Sub code x=0.0...
from django import template from waffle import flag_is_active, sample_is_active, switch_is_active register = template.Library() class WaffleNode(template.Node): def __init__(self, nodelist_true, nodelist_false, condition, name): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_...
# -*- coding: utf-8 -*- from django.contrib.sitemaps import Sitemap from ionyweb.page.models import Page class PagesSitemap(Sitemap): changefreq = "weekly" priority = 0.5 def items(self): return Page.objects.filter(draft=False) def lastmod(self, obj): return obj.last_modif
import warnings import pandas as pd from skopt import Optimizer from .tuner import Tuner from .tuner_exceptions import ParameterError from evalml.utils import deprecate_arg from evalml.utils.logger import get_logger logger = get_logger(__file__) class SKOptTuner(Tuner): """Bayesian Optimizer.""" def __in...
from twisted.internet import reactor from txjsonrpc.web.jsonrpc import Proxy import jsonpickle import sys import os sys.path.append("/home/fhuici/research/eu/demons/svn/Sources/blockmon/main/node/daemon/") from core.returnvalue import * from core.host import HostSpecsInfo from core.block import * DAEMON_PORT = 7080 d...
from .roland_piano import RolandPiano from .roland_utils import discover from .roland_address_map import RolandAddressMap from .roland_instruments import Instruments
# Copyright 2020 Google LLC # # 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 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python2 # Copyright (c) 2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test mulitple rpc user config option rpcauth # from test_framework.test_framework import ClarityTestFrame...
import torch from torch.nn.modules.batchnorm import _BatchNorm as origin_BN '''reimplement BN in module but not function''' class _BatchNorm(origin_BN): @staticmethod def expand(stat, target_size): if len(target_size) == 4: stat = stat.unsqueeze(1).unsqueeze(2).expand(target_size[1:]) ...
from _main_.utils.massenergize_errors import MassEnergizeAPIError from _main_.utils.massenergize_response import MassenergizeResponse from _main_.utils.common import serialize, serialize_all from api.store.graph import GraphStore from _main_.utils.context import Context from typing import Tuple class GraphService: "...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import glob import argparse import numpy as np from PIL import Image def main(): parser = argparse.ArgumentParser() parser.add_argument("--data_path", help="Path to ORBIT benchmark dataset root") args = parser.parse_args()...
#!/usr/bin/env python # -*- coding:utf-8 -*- import xml.etree.ElementTree as ET import lxml.html from lxml import etree from lxml.html.soupparser import fromstring import re _badtags = set(["script", 'style' , 'iframe']) _have_a_chars = re.compile(r'\w', re.UNICODE) _splitter_chars = re.compile(r'[\s,]', re.UNICODE) ...
#!/usr/bin/env python import csv import sys import matplotlib.pyplot as plt from tracemalloc import start import time from TrajectoryUtils import TrajectoryUtils from TrajectoryUtils import euclidianDistance sys.path.append("../..") from planner.cbFunctions import heuristicFunction from pycrazyswarm import Crazyswarm...
"""The motion_blinds component.""" from datetime import timedelta import logging from socket import timeout from motionblinds import MotionMulticast from motionblinds.motion_blinds import ParseException from homeassistant import config_entries, core from homeassistant.const import CONF_API_KEY, CONF_HOST, EVENT_HOMEA...
import os from urlparse import urljoin, urlparse from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.options import ModelAdmin from django.contrib.staticfiles import finders from django.core.exceptions import PermissionDenied from django.c...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `taurus_pyqtgraph` package.""" from click.testing import CliRunner def test_smoke(): import taurus_pyqtgraph # noqa def test_command_line_interface(): """Test the CLI.""" from taurus_pyqtgraph import cli runner = CliRunner() result ...
import numpy as np import os import pickle import unittest import wkb_raster class TestWKBRasterWrite(unittest.TestCase): def setUp(self): self.data_dir = os.path.abspath( os.path.join( os.path.dirname(__file__), 'data' ) ) self.so...
from pathlib import Path import os from quest import Quest RESOURCE_PATH = Path('resources') QUESTS_PATH = RESOURCE_PATH / 'quests' IMAGES_PATH = RESOURCE_PATH / 'images' BATTLEPLANS_PATH = RESOURCE_PATH / 'battleplans' class AutoFable: def __init__(self): self.quests = [] def load(self): """...
import sys import subprocess import os path = "/home/rahultarak12345/UofTHacks-2020/ML/testImage/" accuracy_dict = {} acc = 0 total = 0 count = 0 for filename in os.listdir(path): count += 1 num = filename.split('-')[0] model_output = subprocess.check_output(['python3', 'label_image.py', path + filename]) ...
import random import secrets from dateutil.relativedelta import relativedelta from django.utils.timezone import now from posthog.constants import TREND_FILTER_TYPE_ACTIONS from posthog.demo.data_generator import DataGenerator from posthog.models import Action, ActionStep, Dashboard, EventDefinition, Insight, Person, ...
def k_th_smallest_distance(nums): nums_pairs = [] for i in nums: for j in nums[i:]: nums_pairs.append((i, j)) return nums_pairs nums = [1, 3, 1] print(k_th_smallest_distance(nums)) def k_th_smallest_distance(nums): nums.sort() for index in range(k):
# created by Tom Stesco tom.s@ecobee.com import attr import pandas as pd import numpy as np from BuildingControlsSimulator.StateEstimatorModels.StateEstimatorModel import ( StateEstimatorModel, ) from BuildingControlsSimulator.DataClients.DataStates import STATES from BuildingControlsSimulator.Conversions.Convers...
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
import os import sys from pathlib import Path from uuid import uuid4 from environ import environ here = os.path.dirname(__file__) sys.path.append(os.path.abspath(os.path.join(here, '..', '..'))) BASE_DIR = Path(__file__).resolve(strict=True).parents[3] env = environ.Env( DEBUG=(bool, False), STATIC_ROOT=(st...
from .bubble_sort import * from .merge_sort import * from .insertion_sort import * from .selection_sort import *
#!/usr/bin/env python3 # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including with...
# -*- coding: utf-8 -*- from unittest import TestCase from unittest.mock import MagicMock from scheduler.spawners.templates.env_vars import get_resources_env_vars class TestEnvVars(TestCase): def test_get_resources_env_vars(self): env_vars = get_resources_env_vars(None) assert any(item.name == 'N...
import pygame from pygame.locals import * pygame.init() screen_width = 1000 screen_height = 800 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Brick Breaker Game") #Font font = pygame.font.SysFont('Ludica', 40) # Colors bg = (234, 218, 184) block_red ...
# Copyright (C) 2021 ycmd contributors # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ycmd...
''' Truncated Product Method: (Zaykin, Genet Epidemiol. 2002) ''' from tpm import tpm import numpy as np import time def combine_pvalues(pvalues, tau=0.05, seed=time.time(), nperms=1000): ''' returns: pvalue pvalues: list of floats tau: (used for tpm) between 0 and 1 ...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dialog.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ItemOrderVO(object): def __init__(self): self._ext_info = None self._item_order_no = None self._merchant_fund = None self._platform_fund = None self._price...
import torch from torch import nn import torch.nn.functional as F class ContentLoss(nn.Module): """ Content Loss for the neural style transfer algorithm. """ def __init__(self, target: torch.Tensor, device: torch.device) -> None: super(ContentLoss, self).__init__() batch_size, channe...
# Generated by Django 2.2.3 on 2019-07-19 15:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ticket', '0002_auto_20190719_1500'), ('flight', '0001_initial'), ] operations = [ migrations.AddFie...
# -*- coding: utf-8 -*- from datetime import timedelta from copy import deepcopy import pytz from django.utils import timezone from django.core.management import call_command import pytest from events.auth import ApiKeyUser from .utils import versioned_reverse as reverse from events.tests.utils import assert_event_...
import csv import math import re import subprocess from functools import reduce from itertools import islice from standard_lib import StdLib from path_helper import PathHelper from operator import itemgetter class Parser: def __init__(self, seconds=0, clients=0, set_observed=None, get_observed=None, ...
"""Training related classes and functions.""" import abc import contextlib import time import tensorflow as tf from opennmt.optimizers import utils as optimizer_util from opennmt.utils import misc class Trainer(abc.ABC): """Base class for model trainer.""" def __init__(self, checkpoint, is_master=True): "...
from discord.ext.commands import command from discord.ext.commands.context import Context from exceptions import PermissionDenied, InvalidArgs, OutOfServer from tools import find_member from cogs import BaseCog class Members(BaseCog): admin = True @command(brief="ban member") async def ban(self, ctx: Co...
from django.http import HttpResponse from django.views.decorators.http import require_GET @require_GET def robots_txt(request): lines = [ 'User-Agent: *', 'Disallow: /admin/', 'Disallow: /account/', ] return HttpResponse('\n'.join(lines), content_type='text/plain')
#!/usr/bin/env python import random import sys while 1: collisionCount = 0 for test in range(100): bucketChoices = set() for i in range(2500): r = random.randint(0,10**6 - 1) if r in bucketChoices: collisionCount += 1 break e...
""" factor.py """ from functools import wraps from operator import attrgetter from numbers import Number from math import ceil from numpy import empty_like, inf, nan, where from scipy.stats import rankdata from zipline.errors import BadPercentileBounds, UnknownRankMethod from zipline.lib.normalize import naive_groupe...
import unittest import compgraph as cg class GraphTests(unittest.TestCase): def tearDown(self): cg.Graph.clear_default() def test_use_different_graph(self): new_graph = cg.Graph() with new_graph.as_default(): node = cg.Node(name='nodo1') self.assertEqual(len(new_g...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView from accounts.models import UserProfile...
import random import math from random import randint import pickle as pkl import numpy as np import torch import tree from operator import itemgetter random.seed(1) class SymbolsManager(): def __init__(self, whether_add_special_tags): self.symbol2idx = {} self.idx2symbol = {} self.vocab_siz...
from typing import Tuple, Optional import pandas as pd import xarray as xr from sklearn.preprocessing import StandardScaler LEVELS = ["time", "lat", "lon"] # @task # get reference cube def get_reference_cube(data: xr.DataArray) -> pd.DataFrame: """Wrapper Function to get reference cube""" return data.to_data...
""" This module gathers tree-based methods, including decision, regression and randomized trees. Single and multi-output problems are both handled. """ # Authors: Gilles Louppe <g.louppe@gmail.com> # Peter Prettenhofer <peter.prettenhofer@gmail.com> # Brian Holt <bdholt1@gmail.com> # Noel Da...
import numpy as np import utils as ut import os import sys # Read parameters from a file or from the command line: parser = ut.argparser() # print(len(sys.argv)) if len(sys.argv) == 1: # use default name for the parameter file pars = parser.parse_args([ut.default_parameter_file]) else: pars = parser.parse_...
import requests from termcolor import colored def color(s,c='g'): if(c=='g'): return colored(s,"green") elif(c=='y'): return colored(s,"yellow") elif(c=='c'): return colored(s,"cyan") elif(c=='m'): return colored(s,"magenta") elif(c=='r'): return c...
# qubit number=5 # total number=56 import cirq import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from ma...
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.42 Contact: support@ory.sh Generated by: htt...
import db import logging logger = logging.getLogger(__name__) class Url(object): def __init__(self, name, _id, modified_time, urllink, container_id, workspace_id): self.name = name self.id = _id self.modified_time = modified_time self.urllink = urllink self.container_id = c...
"""Simplex method for linear programming The *simplex* method uses a traditional, full-tableau implementation of Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex). This algorithm is included for backwards compatibility and educational purposes. .. versionadded:: 0.15.0 Warnings -------- Th...
from nextcord.ext import commands import json import pymongo import os class AddBadWords(commands.Cog): def __init__(self, client): self.client = client @commands.guild_only() @commands.has_permissions(send_messages=True, manage_messages=True) @commands.command(name="add-bad-words", aliases=...
# Author : skjang@mnc.ai # Date : 2020-12-03 import pandas as pd import os import copy, shutil import torch import torch.nn.functional as F from torch.optim import lr_scheduler import torch.optim as optim import torch.nn as nn from collections import defaultdict # ref : https://github.com/kakaobrain/...
from orator.migrations import Migration class CreateProductCategoriesTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('categories') as table: table.increments('id') # _TODO: name should be unique table.string(...
import unittest import numpy as np import torch from pytorch_metric_learning.distances import CosineSimilarity, LpDistance from pytorch_metric_learning.miners import BatchHardMiner from .. import TEST_DEVICE, TEST_DTYPES, WITH_COLLECT_STATS from ..zzz_testing_utils.testing_utils import angle_to_coord class TestBat...
""" На экзамен по машинному обучению пришло N человек. Определите, из какой группы пришло больше всего студентов, которые сдали экзамен на отлично (>=8). Формат ввода Информация о результатах экзамена записана в файле, в котором каждая из строк имеет вид: фамилия имя группа балл. Фамилия и имя являются строками, групп...
#!/usr/bin/python3 # coding:utf-8 # """ 字符串处理 """ import platform import re def legitimize(text, myos=platform.system()): """Converts a string to a valid filename. credit: soimort/you-get. option: filename. """ # POSIX systems text = text.translate({ 0: None, ...