content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ equip.analysis.dataflow ~~~~~~~~~~~~~~~~~~~~~~~ Different kind of data flow analyzes. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ from .fixedpoint import Dataflow, \ ForwardDataflow, \ ...
""" 'utils.py' implements utility methods for the fuse program. """ from wikipedia import page from string import punctuation from settings import LANGUAGE, Color from wikipedia.exceptions import DisambiguationError from wordfreq import word_frequency as known_freq COM...
from django.shortcuts import render from django.views.generic import CreateView, DetailView, ListView from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.forms.models import model_to_dict from .fo...
if __name__ == '__main__': with open('input0', 'r') as file: start = int(file.readline().strip()) departs = [int(i) if i.isdigit() else False for i in file.readline().split(',')] schedule = {} for idx, d in enumerate(departs): if d: schedule[d] = idx depart_offset = s...
from torch.optim.lr_scheduler import _LRScheduler from torch.optim.lr_scheduler import MultiStepLR from torch.optim.lr_scheduler import ExponentialLR from torch.optim.lr_scheduler import CosineAnnealingLR from torch.optim.lr_scheduler import ReduceLROnPlateau from transformers import get_constant_schedule_with_warmup f...
# simple_rl imports. from simple_rl.planning.PlannerClass import Planner def HierarchicalPlanner(Planner): def __init__(self, mdp_hierarchy, planner): self.mdp_hierarchy = mdp_hierarchy self.planner = planner def plan(self, low_level_start_state): ''' Args: low_level_start_state (simple_rl.State) Ret...
# Copyright 2016 Confluent 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 writing, s...
#!/usr/bin/env python import io from setuptools import setup, find_packages version_tuple = __import__('pymysql').VERSION if version_tuple[3] is not None: version = "%d.%d.%d_%s" % version_tuple else: version = "%d.%d.%d" % version_tuple[:3] with io.open('./README.rst', encoding='utf-8') as f: readme = f...
import binascii import functools import base64 from django.contrib import auth def basic_authentication(func): "Decorator for http basic authentication on views." @functools.wraps(func) def _basic_authentication(request, *args, **kwargs): header_value = request.META.get('HTTP_AUTHORIZATION') ...
# Copyright 2020 ZTE Corporation. # All Rights Reserved. # # 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...
from django.db import models # Template Model class Crypto(models.Model): id = models.IntegerField(primary_key=True, default=0) name = models.CharField(max_length=100) # Name of the stock price = models.CharField(max_length=20) # Opening stock price change = models.Cha...
"""Oral Argument Audio Scraper for Court of Appeals for the Sixth Circuit CourtID: ca6 Court Short Name: 6th Cir. Authors: Brian W. Carver, Michael Lissner Reviewer: None History: 2014-11-06: Started by Brian W. Carver and wrapped up by mlr. """ import re from datetime import datetime from urlparse import urlparse, ...
"""This is the unittest comes with the utils.py, Run `pytest -vv` in the directory after you make any changes to utils.py. TODO: Add more test cases, cover testing the CLI itself. """ import time import hvac import os import pytest import requests_mock import tempfile from unittest.mock import patch from . import ut...
"""openjtalk module command line util """ import io import wave from argparse import ArgumentParser from itertools import chain import pyaudio from . import openjtalk def main(): parser = ArgumentParser() parser.add_argument('-t', '--text') for m in openjtalk.OPTION_MAPPINGS: parser.add_argumen...
import numpy as np from sklearn.datasets import make_blobs from sklearn.tree import export_graphviz import matplotlib.pyplot as plt from .plot_2d_separator import (plot_2d_separator, plot_2d_classification, plot_2d_scores) from .plot_helpers import cm2 as cm, discrete_scatter ...
# Maximum joint number is 10. # a0[0,1,2,3,4,5,6,7,8,9] # a1[0,1,2,3,4,5,6,7,8,9] # ... # a15[0,1,2,3,4,5,6,7,8,9] # Total possible combinations = (Pr10)^(16-1) = (10!)^15 (A huge number.) # So we randomly shuffle them, and if repeats, re-shuffle to get a new one. import numpy as np from common import seeds with s...
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under t...
# Generated by Django 2.1.2 on 2018-11-03 18:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0031_auto_20181103_1226'), ] operations = [ migrations.AlterField( model_name='story', ...
#Criar uma aplicação que leia um número e diga qual número vem depois e antes.
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .utils import skipIfNoTransducer from .torchscript_consistency_impl import RNNTLossTorchscript @skipIfNoTransducer class TestRNNTLoss(RNNTLossTorchscript, PytorchTestCase): device = torch.device('cpu')
import sys import os import argparse import cv2 import torch from torch.autograd import Variable from torchvision import transforms import torch.backends.cudnn as cudnn import torchvision import torch.nn.functional as F from PIL import Image import pandas as pd import my_hopenet import utils from sklearn.decomposition...
import asyncio import pytest from .models import db, User, UserType pytestmark = pytest.mark.asyncio async def test(bind): await User.create(nickname="test") assert isinstance(await User.query.gino.first(), User) bind.update_execution_options(return_model=False) assert not isinstance(await User.que...
import keras from generators.DataGenerator import * def get_model(name): if name == "single": model_path = os.path.join('..', 'models', 'categorical_model_six_full_improved_v5.h5') return keras.models.load_model(model_path, compile=False) elif name == "sequential": multi_model_path = o...
import logging import numpy as np import tensorflow_datasets as tfds from .dataset import Dataset from .preprocessing import apply_normalization, get_feature_preproc_fn, select_num_samples_per_cls,\ split_train_val_given_ratio_val __author__ = 'Otilia Stretcu' CLASS_NAMES = { 'mnist': ['0', '1', '2', '3', '4...
import requests class EmployeeService(object): def __init__(self, api_authorization, api_url, merchant_id): self.url = api_url.rstrip('/') self.merchant_id = merchant_id self.auth = api_authorization # Employees def get_employees(self): # Define Payload payload = {...
# 加载自定义库 import sys from pathlib import Path from importlib import import_module DOC_ROOT = Path(__file__).absolute().parents[2] MOD_PATH = str(DOC_ROOT/'xinetzone/src') # print(MOD_PATH) if MOD_PATH not in sys.path: sys.path.extend([MOD_PATH]) tvmx = import_module('tvmx') # 设定 TVM 项目的根目录 # TVM_ROOT = Path('/med...
from typing import Optional, Any, Type, Union class Node: def __init__(self, value: Union[float, int] = None, left = None, right = None): self.value = value self.left = left self.right = right def __str__(self): return f"Value: {self.value}" class BST: def __init__(self, r...
''' Probem Task : This program will find longest substring with alternating odd/even or even/odd digits Problem Link : https://edabit.com/challenge/RB6iWFrCd6rXWH3vi ''' def LongestAlternativeSubstring(digits): sol = digits[0]; for i in range(1,len(digits)): if (int(digits[i - 1]) % 2 != int(d...
from django.apps import AppConfig class DjangoStoragesConfig(AppConfig): name = "minio_storage"
import json import math import warnings warnings.filterwarnings('ignore') from .logger import logger from GIS_Tools import ProxyGrabber import requests from time import sleep def y2lat(y): return (2 * math.atan(math.exp(y / 6378137)) - math.pi / 2) / (math.pi / 180) def x2lon(x): return x / (math.pi / 180.0...
import numpy as np import scipy def SEIR(x, M_g, M_f, pop, ts, pop0, sd=[]): #the Adaptive metapopulation SEIR model dt = 1. tmstep = 1 #integrate forward for one day num_loc = pop.shape[0] (_, num_ens) = x.shape #S,E,Id,Iu,obs,beta,mu,theta_g,theta_f,Z,alpha,D Sidx = np.arange(1, 5*nu...
# pylint: disable=missing-docstring import unittest from uplink_python.module_classes import ListObjectsOptions from .helper import TestPy class ObjectListTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.test_py = TestPy() cls.access = cls.test_py.get_access() cls.projec...
import json import os from pcf.util.pcf_util import update_dict,particle_class_from_flavor class GenerateParticle: def __init__(self, particle_definition): self.particle_class = particle_class_from_flavor(particle_definition.get("flavor")) self.particle = self.particle_class(particle_definition) ...
import base64 import typing import binascii from hashlib import md5 import crc32c as google_crc32c class crc32c: def __init__(self, data: bytes=None): self._checksum = google_crc32c.Checksum(data) def update(self, data: bytes): self._checksum.update(data) def hexdigest(self) -> str: ...
from setuptools import setup setup( name='pytorch_tps', description='Thin plate spline interpolation for PyTorch', version="0.0.1", author='Yucheol Jung', author_email='ycjung@postech.ac.kr', packages=['pytorch_tps'], url='https://github.com/ycjungSubhuman/pytorch_tps', )
import re from itertools import chain lines = enumerate(open('day-16.input')) rules = {} my_ticket = [] nearby_ticket = [] ## Parsing input code line = None min_rules = 5000 max_rules = 0 while True: line = next(lines) line = line[1].strip() if line == '': break name, value = line.split(': ') value =...
# -*- coding: utf-8 -*- import unittest import tests.common from core.localisation import _ import json class lookTests(tests.common.common): def test_text(self): self.rpg.setAction([_('LOOK_COMMAND')]) output = self.rpg._runAction() self.assertEquals(output, _('CURRENT_REGION_%s') % 'The High lands\n' +\ ...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created by Mengqi Ye on 2021/12/22 """ from stm import DataTransferModeMachine class TestDataTransferModeMachine: def setup(self): self.machine = DataTransferModeMachine() print() def test_CMD3(self): for i in range(10): ...
from pykrx import stock # PER 0인 종목 필터링 df = stock.get_market_fundamental_by_ticker(date="20100104", market="KOSPI") cond = df["PER"] != 0 df = df[cond] # PER이 낮은 n개 종목 선정 low_per = df["PER"].nsmallest(n=2) print(low_per)
#!/usr/bin/env python3 import code import os import requests from bs4 import BeautifulSoup import re import getpass import argparse import logging # props to https://gist.github.com/brantfaircloth/1443543 class FullPaths(argparse.Action): """Expand user- and relative-paths""" def __call__(self, parser, namesp...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Telegram bot @RaspberyPi3Bot """ """ from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job import telegram import logging import pickle import os from subprocess import call import datetime import sys if not 'win' in sys.plat...
from shapes import * class Game(QWidget): def __init__(self, width=50, height=50, gridstep=10): super().__init__() self.setWindowTitle("Игра в жизнь") self.color = QBrush(QColor(0, 0, 0)) self.delay = 10 self.height_button = 50 self.width_button = width * gridstep...
from talon import Module, Context mod = Module() mod.tag("terraform", desc="tag for enabling terraform commands in your terminal")
import json from mock import Mock from twisted.python import failure from twisted.test.proto_helpers import MemoryReactorClock from synapse.api.errors import InteractiveAuthIncompleteError from synapse.http.server import JsonResource from synapse.rest.client.v2_alpha.register import register_servlets from synapse.ut...
class User: ''' class to generate new instances of users ''' user_list = [] #empty list to append users def __init__(self,first_name,last_name,email,user_name,password): ''' method to define the properties of the object ''' self.first_name = first_name self.l...
def leiadinheiro(msg): validade = False while not validade: entrada = str(input(msg)).replace(',', '.').strip() if entrada.isalpha() or entrada == "": print(f'Erro! {entrada} não é um preço válido') else: validade = True return float(entrada) def lei...
# -*- coding: utf-8 -*- import scrapy from ..items import AmazonItem from scrapy.http import Request class AmazonscraperSpider(scrapy.Spider): name = 'amazon' keyword = input("Enter the keyword to search: ") start_urls = [ "https://www.amazon.in/s?k="+ keyword +"&ref=nb_sb_noss_2" ] def parse(...
from win10toast import ToastNotifier import time notifier = ToastNotifier() while True: if (time.gmtime().tm_min) % 15 == 0: notifier.show_toast("Break!", "Stretch a bit..You're awesome", duration=15) time.sleep(60)
#!/bin/env python from tornado import gen from tornado.ioloop import IOLoop from .. import metrics @gen.coroutine def main(): data = yield metrics.remote_classifier_report("http://localhost:3002/", "bnn", "bst", "drone", auth_username="bst", auth_password="bst", model_params={"hiddenLayers...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
# -*- coding: utf-8 -*- import pytest import urllib3 def test_the_tests(): """ to test the tests configuration """ assert True is True @pytest.mark.vcr() def test_vcr(): """ Test VCR.py records and plays http requests properly """ http_manager = urllib3.PoolManager() response = ...
import os import shutil from bin.bb8.settings import Settings from bin.bb8.targets import NamedVolumeTarget, TargetOptions, DirectoryTarget json = """{ "starport": { "addr": "the moon", "ip": "127.0.0.1", "user": "astronaut", "backup_location": "houston" }, "targets": [ ...
from datetime import timedelta import json import os import requests import tornado from notebook.services.contents.largefilemanager import LargeFileManager METADATA_TTL = timedelta(minutes=5) class WelderContentsManager(LargeFileManager): """ A contents manager which integrates with the Leo Welder service. Bl...
import numpy as np a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j]) print("Original array") print(a) print("Checking for complex number:") print(np.iscomplex(a)) print("Checking for real number:") print(np.isreal(a)) print("Checking for scalar type:") print("3.1 is scalar:", np.isscalar(3.1)) print("[3.1] is scalar:", np.issc...
"""This module contains parser tooling for the zeekscript package.""" import os import pathlib import sys try: # In order to use the tree-sitter parser we need to load the TS language .so # the TS Python bindings compiled at package build time (via our setup.py # tooling). We use the following helpers whe...
#! /usr/bin/python """OT Linearization. Usage: otlinearize.py [options] otlinearize.py tableau [options] <tree> otlinearize.py typology [options] <trees>... otlinearize.py typology [options] -f <treelist> Options: -h, --help Show this screen. --version Show version. -t ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: required = f.read().splitlines() about = {} with open("tnscm/_version.py") as f: exec(f.read(), about) setuptools.setup( name="tnscm", version=about["__version__"],...
import yaml import subprocess with open('./profiles.yml','r') as f: profile = yaml.safe_load(f.read()) for target in profile['default']['outputs']: subprocess.call(['dbt','seed', '--profiles-dir','.','--target', target])
# Generated by Django 3.0.8 on 2021-04-23 14:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tnris_org', '0033_auto_20201215_0949'), ] operations = [ migrations.AddField( model_name='tnrisimage', name='carouse...
import socket import time import sys conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect(("127.0.0.1", 14900)) conn.send(b"Hello, server \n") data = conn.recv(16384) udata = data.decode("utf-8") print(udata) conn.close()
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Nombre: fuenteAplicacion.py # Autor: Miguel Andres Garcia Niño # Creado: 20 de Mayo 2018 # Modificado: 20 de Mayo 2018 # Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018 # License: ...
import random from example.commons import Faker from pyecharts import options as opts from pyecharts.charts import Scatter3D def test_scatter3d_base(): data = [ [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)] for _ in range(80) ] c = ( Scatter3D() ...
import unittest import os import time import urllib2 from ledger.transaction.endpoint_registry import EndpointRegistryTransaction from txnintegration.exceptions import ValidatorManagerException, ExitError from txnintegration.integer_key_client import IntegerKeyClient from txnintegration.utils import generate_privat...
import circuitcourtparser import districtcourtparser import logging import sys from circuitcourtopener import CircuitCourtOpener from districtcourtopener import DistrictCourtOpener from time import sleep log = logging.getLogger('logentries') class DistrictCourtReader: def __init__(self): self.searches_on_...
#!/usr/bin/python # -*- coding: utf-8 -*- import requests import codecs import json import xmltodict import sys import os import difflib import xbmc import xbmcgui import xbmcaddon import qrcode def annictRecord(AnnictEpisodeID, annictToken): url = "https://api.annict.com/v1/me/records" payloads = { "a...
import unittest from df_utils import UtilityFunctions class SqrtTests(unittest.TestCase): """Functions to test the increment of attributes """ ut = UtilityFunctions() def test_raise_power(self): #ut = UtilityFunctions() self.assertEqual(ut.raise_power(5,2),25) def test_raise_pow...
from django.contrib import admin # Register your models here. from .models import User, UserBill, Bill, Flat admin.site.register(User) admin.site.register(UserBill) admin.site.register(Flat) admin.site.register(Bill)
from distutils.core import setup setup( name='foorep', version='0.1.4-2', author='Johan Berggren', author_email='jbn@klutt.se', packages=['foorep', 'foorep.test'], url='http://foorensics.blogspot.com', license='LICENSE.txt', description='Malware Repository for humans', long_descript...
# This is a generated file so don`t change this manually. # To re-generate run 'python gen-dependency-info.py <GitHub_PAT>' from the project root. LICENSES = [ { "Name": "adal", "Version": "1.2.7", "Summary": "Note: This library is already replaced by MSAL Python, available here: https://py...
####################################################################################################################################################### #CopyRight: This software tool is a copyright of the author. Please take permission before use or modification. #Author: Abhishek Narain Singh #Description: This code i...
from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.color import ColorTable from echomesh.util.TestCase import TestCase class TestColorTable(TestCase): def test_black(self): self.assertEqual(ColorTable.to_color('black'), (0.0, 0.0, 0.0)) def test_white(self): ...
from calendar import day_name from math import floor from .Translator import Translator from .Rule import Rule class Pattern: """Class that represents a pattern composed of a set of rules, number of samples, impurity and number of positive and negative examples""" def __init__(self, rules, total_pos, to...
# coding: utf-8 # ----------------------------------------------------------------------------------- # <copyright company="Aspose"> # Copyright (c) 2018 Aspose.Slides for Cloud # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associa...
import xbmc xbmc.executebuiltin( "PlayMedia(/media/MEDIA/autoplay.m3u)" ) xbmc.executebuiltin( "PlayerControl(RepeatAll)" )
from ._C_nqs.optimizer import *
import numpy as np import torch import torch.nn as nn from .functions import dice, get_activation_func class DiceLoss(nn.Module): def __init__( self, eps: float = 1e-7, activation: str = 'none', reduction: str = 'mean' ): super().__init__() self.eps = eps ...
# MIT licensed # Copyright (c) 2020 lilydjwg <lilydjwg@gmail.com>, et al. # Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al. from flaky import flaky import pytest pytestmark = [pytest.mark.asyncio, pytest.mark.needs_net] @flaky(max_runs=10) async def test_debianpkg(get_version): assert await get_v...
# -*- coding: utf-8 -*- ''' File name: code\the_chase\sol_227.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #227 :: The Chase # # For more information see: # https://projecteuler.net/problem=227 # Problem Statement ''' "The Chase" is ...
# -*- coding: utf-8 -*- ######## # Copyright (c) 2015 Fastconnect - Atost. All rights reserved # # 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/LICENS...
import logging import os import time def mount_plentyfs(ctx, dirname=None, options=None): logging.info(f"starting plentyfs at {dirname} with options {options}") srcdir = globals()["srcdir"] _daemon_start = globals()["_daemon_start"] os.mkdir(dirname) plentyfs = os.path.join(srcdir, "target", "de...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: third_party/openapi/v1/openapi.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool...
import sys import time import numpy as np # Download and install the Python COCO tools from https://github.com/waleedka/coco # That's a fork from the original https://github.com/pdollar/coco with a bug # fix for Python 3. # I submitted a pull request https://github.com/cocodataset/cocoapi/pull/50 # If the PR is merged ...
# coding:utf-8 import numpy as np import pandas as pd import pickle import os from settings import DATA_DIR def deepfm_onehot_representation(sample, fields_dict, array_length): array = np.zeros([array_length]) idxs = [] for field in fields_dict: if field == "click": continue if...
# -*- coding: utf-8 -*- """ flask-snippets.template ~~~~~~~~~~~~~~~~~~~~~~~ Template Python file for flask-snippets. """ import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from flask import request, Response from app import app @app.route('/') def inde...
from datetime import date, timedelta import logging from smtplib import SMTPException from django.conf import settings from django.core.mail import send_mail from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from .m...
import time class Memoize(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if args in self.cache: return self.cache[args] ret = self.func(*args) self.cache[args] = ret return ret @Memoize ...
#!/usr/bin/env python3 from metasploit import module, probe_scanner metadata = { 'name': 'Open WAN-to-LAN proxy on AT&T routers', 'description': ''' The Arris NVG589 and NVG599 routers configured with AT&T U-verse firmware 9.2.2h0d83 expose an un-authenticated proxy that allows connec...
import random import sys for line in sys.stdin: line = line.rstrip("\n\r") try: newline = [' ' for c in line] indexes = list(range(len(newline))) random.shuffle(indexes) for i in indexes: newline[i] = line[i] sys.stdout.write('\r') sys.stdout....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Flask main script.""" # Run locally # export HOST=0.0.0.0 # 0.0.0.0 or localhost # export PORT=8000 # gunicorn -w 1 --bind $HOST:$PORT main:app # Heroku App name = {{cookiecutter.flask_app_name}} # export FLASK_APP_NAME={{cookiecutter.flask_app_name}} # Heroku P...
#!/usr/bin/env python from subprocess import Popen, PIPE import sys import os os.chdir("storm-core") ns = sys.argv[1] pipe = Popen(["mvn", "clojure:repl"], stdin=PIPE) pipe.stdin.write("(do (use 'clojure.test) (require '%s :reload-all) (run-tests '%s))\n" % (ns, ns)) pipe.stdin.write("\n") pipe.stdin.close() pipe....
# -*- coding: utf-8 -*- """Example of one-time token with "encoding" for additional security level. """ import json from datetime import datetime import ckan.plugins as p import ckan.model as model class ExampleIApiTokenPlugin(p.SingletonPlugin): """Example of plugin, that allows every token to be used only onc...
def parse_minizinc_output(): board_raw = """P I N A T A P A N E R A S M L B V N O Y A V E E U R O P E O E O R E I F B Z C E M S L U R P R Z N U N B E R L Z H N P E Q E J B C D L I B C N A E I O T E P U A E A O E C L O O N N T F S E H C E T L N E E E F T S A C F R E S C A R P L O Q C F O C M V E R A H S C O N E S U ...
import pytest from django.urls import reverse from harrastuspassi.models import Organizer @pytest.mark.django_db def test_organizer_list_returns_only_editable_for_authenticated_user(user_api_client, user2_api_client, api_client): """ Organizer endpoint should return only editable organizers for authenticated user...
import numpy as np import os import urllib.request import gzip import struct def download_data(url, force_download=True): fname = url.split("/")[-1] if force_download or not os.path.exists(fname): urllib.request.urlretrieve(url, fname) return fname def read_data(label_url, image_url): wit...
''' Users URL Configuration ''' from django.urls import path from . import views urlpatterns = [ path('user/signup/', views.signup_user), path('user/signin/', views.signin_user), path('user/change_password/', views.change_password_user), path('comment/add/', views.add_comment), path('comment/delete...
# Copyright (c) OpenMMLab. All rights reserved. from copy import deepcopy from functools import partial from typing import Any, Dict, Optional, Sequence, Tuple, Union import torch from mmdeploy.apis.core import PIPELINE_MANAGER from mmdeploy.core import RewriterContext, patch_model from mmdeploy.utils import Backend,...
# -*- coding: utf-8 -*- """ Shorthands for type constructing, promotions, etc. """ from __future__ import print_function, division, absolute_import import inspect from numba.typesystem import types, universe from numba.typesystem.types import * __all__ = [] # set below integral = [] unsigned_integral = [] floating ...
from setuptools import setup, find_packages setup(name='distance_sensor_118X', version='0.1', description = 'interface to the micro-epsilon optoNCDT ILR 118X laser distance sensors.', author = 'William Dickson, IO Rodeo Inc.', author_email = 'will@iorodeo.com', packages=find_packages(), ...
import math import sys if __name__ == '__main__': area = int(sys.stdin.readline().strip()) print(math.sqrt(area) * 4)
import numpy as np weights = { 'excellent': 3, 'good': 2, 'fair': 1 } data = np.array([ 'excellent', 'fair', 'good', 'excellent' ]) # Parsing the categories to weights data = np.fromiter(map(lambda x: weights[x], data), dtype=np.int) # Creating a zero matrix for the Proximity measure...