content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division from celery.app import app_or_default from django.core.management import BaseCommand class Command(BaseCommand): help = 'Flush celery queue' def handle(self, *args, **options): n = app_or_default().control.purge() pri...
from pyspark.sql import SparkSession from pyspark.sql.functions import * # Start Spark Session spark = SparkSession.builder.getOrCreate() # Read data data = spark.read.csv('/project2/macs30123/AWS_book_reviews/*.csv', header='true', inferSchema='true') # Recast ...
import re def anyof(*args): return r'(?:%s)' % '|'.join(args) def join(*args): tokens = [] for tok in args: if isinstance(tok, (list, tuple)): tok = '(%s)' % r'\s*'.join(tok) tokens.append(tok) return r'\s*'.join(tokens) lparen = r'\(' rparen = r'\)' colon = r'\:' a...
import json import pytest import requests from mockserver_client.mockserver_client import ( MockServerFriendlyClient, mock_request, mock_response, times, ) from mockserver_client.mockserver_verify_exception import MockServerVerifyException def test_mock_server_inline_fail() -> None: test_name = ...
import itertools from collections import deque class STATUS: READY = 0 COMPLETE = 1 WAIT = 2 class OP: SUM = 1 MUL = 2 INPUT = 3 OUTPUT = 4 JUMP_IF_TRUE = 5 JUMP_IF_FALSE = 6 LESS_THAN = 7 EQUALS = 8 HALT = 99 class MODE: POSITION = 0 IMMEDIATE = 1 class Parameter: def __init__(self, mode, value)...
""" Single source of truth for version number """ __version__ = "0.0.10"
# coding:utf-8 """ This code generates tensors for detecting thin edges and boundaries, and their orientations. """ import itertools import math as m import numpy as np from slam_recognition.util.attractor import euclidian_attractor_function_generator as __euclid_function_generator from slam_recognition.util.normal...
#!/usr/bin/python3 from db import Database db = Database() db.create()
from functions_elm_aero import * neurons = 8 base, rows = open_csv_aero('../datasets/aero.dat') train, test = split_dataset(base, rows, "holdout") base_i, base_o = extract_io(base, rows) train_i, train_o = extract_io(train, len(train)) test_i, test_o = extract_io(test, len(test)) training_final, weights_hl, weights_o...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import sorl.thumbnail.fields import peripteras.kiosks.models class Migration(migrations.Migration): dependencies = [ ('kiosks', '0008_kiosk_info'), ] operations = [ migrations.AddFie...
from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["SpecialArrangements"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class SpecialArrangements: """ Special arrangements This value set defines ...
import pandas as pd class Statistics(object): def __init__(self, series, chart_type='pie'): self.chart_type = chart_type self.chart = {'type': chart_type, 'data': []} if chart_type == 'pie' else {'type': chart_type, 'data': {'name': [], 'value': []}} def append(self, row): if self.chart_type == 'pie': sel...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014 Contributor # # 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...
# Generated by Django 2.2.8 on 2020-01-12 11:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('post', '0007_auto_20200112_1112'), ] operations = [ migrations.AlterField( model_name='adminprofile', name='bio', ...
from django.db import models from django.contrib.auth.models import User # Create your models here. # resources, event, comment class Resources(models.Model): resourcename=models.CharField(max_length=255) resourcedescription=models.CharField(max_length=255, null=True, blank=True) def __str__(self): ...
from django import forms from django.db.models import fields from . import models class SearchForm(forms.Form): query = forms.CharField(label = "") class BookForm(forms.ModelForm): class Meta: model = models.Book fields='__all__'
class MenuHelper: def __init__(self, app): self.app = app def home(self): wd = self.app.wd wd.find_element_by_link_text("home").click() def groups(self): wd = self.app.wd wd.find_element_by_link_text("groups").click()
import numpy as np import pandas as pd from BioReactor.utils import loadDataFrame import matplotlib.pyplot as plt import os class perfusionProcessor(object): """Creates an object of class perfusionProcessor Args: data_dir: str Directory where input data is located dataFiles: li...
def binary_search(array, data): l= 0 r = len(array) - 1 while l <= r: m = l + (r - l) // 2 if array[m] == data: return m elif array[m] < data: l = m + 1 else: r = m - 1 return -1 if __name__ == "__main__": input_array = [ 2, 3, 4,...
#automate in directory import xlwt import os import sys import hbond_out import make_xl_ab def make_excel(d,suffix): wb=xlwt.Workbook() sheet = wb.add_sheet('Version1') col=0 for bond in d: row=0 lis=d[bond] sheet.write(row,col,bond) row+=1 for a,b,c in lis: sheet.write(row,col,float(a)) if suffi...
name=input("What is your name?\n") age=input("How old are you?\n") city=input("Where do you live?\n") print("Hello,"+ name) print("Your age is " + age) print("You live in " + city)
import json import unittest from os.path import dirname, join from conda.resolve import MatchSpec, Package, Resolve with open(join(dirname(__file__), 'index.json')) as fi: r = Resolve(json.load(fi)) f_mkl = set(['mkl']) class TestMatchSpec(unittest.TestCase): def test_match(self): for spec, res ...
# Copyright 2016 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. from google.appengine.ext import ndb from common.findit_http_client import FinditHttpClient from common.waterfall import failure_type from gae_libs.gitiles....
#!/usr/bin/env python3 # -*- coding = utf-8 -*- import inspect import functools from chemsolve.element import Element from chemsolve.utils.periodictable import PeriodicTable from chemsolve.utils.errors import InvalidElementError from chemsolve.utils import constants def check_empty_values(*params, allow = 1, maybe_le...
def is_url(url: str) -> bool: return URL(url).is_url from urlfinderlib.url import URL from urlfinderlib.urlfinderlib import get_url_permutations, find_urls
''' На плоскости дано множество точек. Найти такой треугольник с вершинами в этих точках, у которого разность площадей треугольника и вписанного круга максимальна. ''' from math import pi, sqrt from tkinter import Tk, Canvas, Label, Entry, Button, DISABLED, messagebox, Menu WINDOW_WIDTH40WINDOW_HEIGHT = 630 WINDOW_...
''' Author 604829050@qq.com https://blog.csdn.net/elecjack/article/details/51532482 ''' import scrapy from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait #from buluo.items import BuluoItem class MySpiderForEastMoney(scrapy.Spider): name = 'zjlx' #start_urls = ['http://da...
class Level: NONE = 0 FIELD = 1 WALL = 10 HEAD = 20 TAIL = 30 APPLE = 40 EXIT = 50 def __init__(self, lines): self.apple_count = 0 self.start_addr = 0 self.growth = 0 self.timer = 0 self.apple_timer = 0 self.width = 0 self.height = 0 self.data = None ...
import os import folium # Importing explicitly the module from 'folium' - 'folium.plugins' import folium.plugins as plugins ''' *************************************** Generating Folium Base Map **************************************''' # Generating a 'Leaflet' map for the location in interest by passing through the ...
import typing as t import jank from .renderer import Renderer class RectRenderer(Renderer): def __init__( self, width: float, height: float, colour: t.Tuple[int, int, int] = (255, 255, 255), batch: t.Optional[jank.graphics.Batch] = None, group: t.Optional[jank.graphics.Gr...
import numpy as np def betaratio(kv, kb, prob, err=None, perframe=True): """Calculate speckle contrast from photon probability ratios.""" prob = np.ma.array(prob, mask=np.zeros_like(prob, dtype=np.bool)) kb = np.ma.array(kb, mask=kb == 0) beta = np.ma.array(np.zeros((kv.size - 1, kb.size))) dbeta ...
def eleva_potencia_cc(a,b): ''' Eleva número "a" a la "b" potencia. Insumo (input): a: número b: número Producto (output): resultado: un número ''' z_var = 11 c = 10 + z_var resultado = a**b + c return resultado def eleva_potencia_dd(a,b): ''' Elev...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###...
print("Hello World! 2nd")
from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.flood import stations_level_over_threshold, stations_highest_rel_level # noqa from floodsystem.analysis import risk_by_gradients import matplotlib.pyplot as plt # requirement # noqa # ---------------------------------...
import os from django.http import HttpResponseForbidden from bluebottle.bluebottle_utils.utils import get_client_ip from apps.organizations.models import Organization, OrganizationMember, OrganizationAddress, OrganizationDocument from apps.organizations.permissions import IsOrganizationMember from apps.organizations.se...
import json import logging from apps.utils.aws.sns import _sns_text_based_notification from apps.utils.data_helpers.manager import DataManager from apps.utils.timezone_utils import str_utc from ..action import BaseAction logger = logging.getLogger(__name__) class CusAction(BaseAction): REQUIRED_EXTRA_KEYS = ['...
from __future__ import division from __future__ import absolute_import import pytest import numpy as np from numpy.testing import assert_allclose from keras.models import Model, Sequential from keras.layers import Input, Dense, Flatten, Concatenate from rl.agents.ddpg import DDPGAgent from rl.memory import Sequentia...
import logging import os from google.appengine.api import app_identity from google.auth import app_engine from google.oauth2 import service_account import googleapiclient.discovery from django.apps import apps from djangae.environment import is_production_environment from .utils import get_backup_setting, get_back...
#!/usr/bin/env python # coding: utf-8 # In[1]: import cv2 import matplotlib.pyplot as plt import numpy as np import random # In[2]: # Read image and convert them to gray!! we need to use rgb2gray not bgr2gray def read_image(path): img = cv2.imread(path) img_gray= cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) ...
#!/usr/bin/env python #encoding: utf8 import sys, rospy, math from pimouse_ros.msg import MotorFreqs from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.srv import TimedMotion class Motor(): def __init__(self): if not self.set_power(False): sys.exit(1) ...
import requests def get_matches( since, count=1000, game="aoe2de", language="en"): assert isinstance(since, int) params = { "since": since, "count": count, "game": game, "language": language } resp = requests.get("https://aoe2.net/api/mat...
'''Utility routines that add in file access''' try: from ..common_util import util as ut except: from common_util import util as ut import json ############################# # Exceptions ############################# class Error(Exception): """Base class for exceptions.""" class FileError(Error): def __init...
from django.shortcuts import render # from profiles.models import Profile # from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Profile # User = get_user_model() # Create your views here. @login_req...
# This file encapsulates the various prediction algorithms that take a trip and return a label data structure # Named "inferrers.py" instead of "predictors.py" to avoid a name collection in our abbreviated import convention import logging import random import copy import emission.analysis.modelling.tour_model_first_o...
# # $Copyright (c) 2019 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors.$ # Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Softwar...
# -*- coding: utf-8 -*- from ipodio import __version__ from setuptools import setup, find_packages setup( name='ipodio', version=__version__, description='iPod command line managing tool', author='Javier Santacruz', author_email='javier.santacruz.lc@gmail.com', url='https://github.com/jvrsant...
# pylint: disable=missing-module-docstring # pylint: disable=missing-function-docstring from pathlib import Path from setuptools import setup from youconfigme import __version__ def read_readme(): readme_f = Path(__file__).parent / 'README.md' with open(readme_f) as f: return f.read() setup( n...
# early_exit_experiments.py # runs the experiments in section 5.1 import torch import numpy as np import aux_funcs as af import model_funcs as mf import network_architectures as arcs from profiler import profile_sdn, profile def early_exit_experiments(models_path, device='cpu'): sdn_training_type = 'ic_only'...
''' 求出 MK 平均值 给你两个整数 m 和 k ,以及数据流形式的若干整数。你需要实现一个数据结构,计算这个数据流的 MK 平均值 。 MK 平均值 按照如下步骤计算: 如果数据流中的整数少于 m 个,MK 平均值 为 -1 ,否则将数据流中最后 m 个元素拷贝到一个独立的容器中。 从这个容器中删除最小的 k 个数和最大的 k 个数。 计算剩余元素的平均值,并 向下取整到最近的整数 。 请你实现 MKAverage 类: MKAverage(int m, int k) 用一个空的数据流和两个整数 m 和 k 初始化 MKAverage 对象。 void addElement(int num) 往数据流中插入一个新的元素 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import array import binascii import contextlib import mmap import sys import numpy import pytest from cybuffer import cybuffer try: from cybuffer import getbuffer except ImportError: getbuffer = memoryview Py_UNICODE_SI...
#!/usr/bin/env python ''' MASVS document parser and converter class. By Bernhard Mueller, updated by Jeroen Beckers and Carlos Holguera Copyright (c) 2021 OWASP Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
import sys import os from ..parameter import pDeepParameter from .. import evaluate as evaluate from . import tune_and_predict # train_folder = sys.argv[1] # test_folder = sys.argv[2] train_Vls = ("/home/pfind/pDeepDev/pDeepData/phospho/PhosSynVelosptmRS/train", 40, "Velos") train_QE = ("/home/pfind/pDeepDev/pDeepD...
from collections import defaultdict from itertools import product def solution(clothes): answer = 1 hash_dict = defaultdict(int) for c, category in clothes: hash_dict[category] += 1 for key in hash_dict: answer *= (hash_dict[key] + 1) answer -= 1 return answer
# Generated by Django 3.0.6 on 2020-05-20 17:49 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('application', '0001_initial'), ('users', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER...
''' Copyright (c) 2017 Vanessa Sochat 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 without limitation the rights to use, copy, modify, merge, publish, distribute...
from src.actions.action import scrap_forum, post_threats from src.actions.no_credentials import NoCredentials from src.authentication.get_token import login from time import sleep from src.lib.logger import setup_logger from logging import getLogger from settings import config setup_logger(config) log = getLogger(__na...
# -*- coding: utf-8 -*- """Configurations for quantization for MicroNet (CIFAR100). - Author: Curt-Park - Email: jwpark@jmarple.ai """ from config.train.cifar100 import micronet config = micronet.config config.update( { "MODEL_NAME": "quant_mixnet", "LR_SCHEDULER_PARAMS": dict(warmup_epochs=0, st...
from django.db import models from django.db.models.fields.related import ForeignKey from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ # Create your models here. class Type(models.Model): name = models.CharField(max_length=125) class Meta: verb...
def is_macro_action(unit_command_action, abilities): """ This function determines if a unit_command action is a macro action based on the following criteria: if the action is related to training, morphing, researching or building units or technologies, then it is a macro action. It returns a boolean. Feel fr...
import json import csv import argparse def unfold_list(base_key, l): new_dict = dict() for i, val in enumerate(l): if isinstance(val, dict): new_k = base_key + '_' + str(i) new_dict.update(unfold(new_k, val)) else: new_dict[base_key] = l return new_dict ...
from time import sleep from colorama import Fore, init init(convert=True) print(f''' ============= PAINEL DE LOGIN ============= sistema para calcular o pesos dos pallet. criado por mim: ZkDragonZk , Estudante De TI =========================================== ''') print('') lastro = int(input('...
#!/usr/bin/env python import json import sys import psycopg2 as psql import spacy def main(): file_path = sys.argv[1] _analyze(file_path) def _analyze(path): connection = psql.connect("dbname=asrdb user=postgres") cursor = connection.cursor() cursor.execute("SELECT raw_data FROM asr_data WHERE...
from app import app, db from flask import request, jsonify from dataclasses import dataclass from sqlalchemy import exc class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True, nullable=False) amount = db.Column(db.Integer, nullable=False) requ...
""" File: 2048_Game Author: Massimo Stefani , Michael Greub Date: 28.12.2018 This is a game of 2048 to be played on the Raspberry SenseHAT. """ # Importation des modules requis from sense_hat import SenseHat from random import randint from time import sleep from time import time import games sense = SenseHat() sense...
from .creators import (create_community_chat, create_group_community, create_member, create_invite_link)
from flask_wtf import FlaskForm # inportation of input fields from from wtforms import StringField, PasswordField, SubmitField, IntegerField, BooleanField, RadioField, TextAreaField # importation of validators from wtforms.validators import Required, Email, EqualTo # custom validator from wtforms import ValidationEr...
import datetime import re from typing import Generator, Text from scrapers.scrapers import Scraper class DnevnikStrategy(Scraper): def get_name(self) -> Text: return 'dnevnik' def get_list_url(self) -> Text: URL = 'https://www.dnevnik.bg/allnews/today/' return URL def list_artic...
#!/usr/bin/env python import rospy import rostest import unittest import sys import tf2_ros __author__ = 'Emiliano Borghi' PKG = 'ca_gazebo' NAME = 'tf_checker' class TfCheckerTests(unittest.TestCase): def __init__(self, *args): # Call TestCase class super(TfCheckerTests, self).__init__(*args) def setU...
"""Tests relating to the PointIsotherm class.""" import pandas import pytest from matplotlib.testing.decorators import cleanup from pandas.testing import assert_series_equal import pygaps import pygaps.utilities.exceptions as pgEx from .conftest import LOADING_AT_PARAM from .conftest import LOADING_PARAM from .conft...
# Copyright (c) 2022 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT import hypothesis.strategies as st import pytest from hypothesis import given, settings from pydantic import AnyUrl, PositiveFloat from pydantic.dataclasses import dataclass as pyd_dataclass from typing_extensions import Literal ...
import os from functools import lru_cache import requests import yaml from ..exceptions import PrefixError ISSUE_BACKEND_API_KEY = os.environ.get("YOUTRACK_TOKEN") YOUTRACK_API_URL = os.environ.get("YOUTRACK_API_URL") ISSUES_ENDPOINT = f"{YOUTRACK_API_URL}/issues" YOUTRACK_PROJECT = os.environ.get("YOUTRACK_PROJE...
from django.test import TestCase from goodbuyDatabase.models import Country, Store, Corporation, Rating, Company, Brand class TestModels(TestCase): def setUp(self): self.country_obj = Country.objects.create( name='Frankreich', code='FR' ) self.store_obj = Store.obj...
#!/usr/bin/env python # coding:utf-8 import cPickle import json import requests path_history = "./history_file/" class UseManiphest: def __init__(self): with open("./web_files/web_message.json", 'r') as load_f: load_dict = json.load(load_f, encoding='UTF-8') self.headers = load_dict[...
# -*- coding: utf-8 -*- import webbrowser from string import Template from constantes import * from helpers import leer_archivo, mostrar_texto class ModeloDePresupuesto: # Datos comerciales titulo = "PRESUPUESTO" encabezado_nombre = "Autotruck Calabozo C.A" encabezado_web = "www.autotruckcalabozo.com.v...
import discord import json from discord.ext import commands import os import psycopg2 class HelpCommands(commands.Cog): def __init__(self,bot): self.bot = bot @commands.group(name='help') async def do_help(self, ctx): if ctx.guild: try: DATABASE_URL = os.environ...
#!/usr/bin/env python3 # Purpose: Submit Spark job to EMR Master Node # Author: Gary A. Stafford (December 2020) # Usage Example: python3 ./submit_spark_ssh.py \ # --ec2-key-path ~/.ssh/emr-demo-123456789012-us-east-1.pem import argparse import logging import boto3 from paramiko import SSHClient,...
"""SearchCV pipeline for incremental hyper-parameter search.""" # Authors: Peter Steiner <peter.steiner@tu-dresden.de>, # Simon Stone <simon.stone@tu-dresden.de> # License: BSD 3 clause import sys if sys.version_info >= (3, 8): from typing import Union, Optional, Callable, Dict, Any, Literal else: from typing ...
""" A `WebView` mixin. Mixin for a window that adds functions to setup `html2` objects. Adds events that control external and internal links. Loads HTML files from our specified data location. Loads HTML from strings and even converts it from Markdown if requested. Licensed under MIT Copyright (c) 2013 - 2017 Isaac M...
import sys sys.path.append('./') import pytest import torch from src.models.mlp import MLP from src.models.cnn import CNN @pytest.mark.parametrize( ["input_shape", "in_features", "num_classes", "hidden_dim"], [ ((2, 1, 28, 28), 784, 10, 200), ], ) def test_mlp_forward(input_shape, in_features, nu...
# SPDX-License-Identifier: Apache-2.0 # Copyright Contributors to the OpenTimelineIO project """Unit tests for the OTIO to SVG adapter""" import os import unittest import tempfile import xml.etree.ElementTree as ET import opentimelineio as otio SAMPLE_DATA_DIR = os.path.join(os.path.dirname(__file__), "...
import abc from semantic_version import Version class InterestingPath(abc.ABC): """ a path which which is important to you in some way. For example, in linux it may be the installation path of a library """ def __init__(self, architecture: int, path: str, version: Version): self.architec...
# -*- Mode: Python -*- # keep the last 10 compilers in case of nasty bugs that are # difficult to back out of. import os import re def rename_binaries(): files = [] for path in os.listdir ('./self'): m = re.match ('^compile([0-9])$', path) if m is not None: num = int (m.group(1)...
from pathlib import Path from typing import Optional from labml import monit from labml.internal import util from labml.internal.lab import WebAPIConfigs _CONFIG_FILE_NAME = '.labml' class Computer: """ ### Computer Lab contains the labml specific properties. """ web_api: WebAPIConfigs uuid...
"""Errors for puckfetcher.""" class PuckError(Exception): """ Generic Exception for errors in this project. Attributes: desc -- short message describing error """ def __init__(self, desc: str) -> None: super(PuckError, self).__init__() self.desc = desc class BadCommandE...
# -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T # # Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # Supporting Flat, xxyx...
# hello_milvus.py demonstrates the basic operations of PyMilvus, a Python SDK of Milvus. # 1. connect to Milvus # 2. create collection # 3. insert data # 4. create index # 5. search, query, and hybrid search on entities # 6. delete entities by PK # 7. drop collection import random import time from pymilvus import ( ...
fibVrednosti = [ 0 : 0, 1 : 1 ] def fib(n): if n in fibVrednosti.keys(): return fibVrednosti[n] else: rezultat = fib(n-1) + fib(n-2) fibVrednosti[n] = rezultat return rezultat rezultat = fib(100) print(rezultat)
print("begin smoke test") import sys import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import tensorflow as tf tf.test.is_gpu_available() print("<<< See GPU info above >>>") import numpy as np import align import argparse import facenet import os import sys import math import pickle from sk...
import urllib.request import cv2 import numpy as np import os def create_pos_n_neg(): for file_type in ['pos']: for img in os.listdir(file_type): print (file_type) if file_type == 'pos': line = file_type+'/'+img+' 1 0 0 200 150\n' ...
class Pipeline: def __init__(self, jobs, context=None): self.jobs = jobs self.context = context or {} def execute(self): for job in self.jobs: job.execute(self.context)
""" The YAML subset accepted by ``demes`` is defined here as a ``strictyaml`` schema. """ from strictyaml import ( CommaSeparated, Map, MapPattern, Float, Int, Optional, Seq, Str, ) Number = Int() | Float() epoch_schema = Map( { Optional("start_time"): Number, "end...
# Copyright 2017 Google Inc. 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 by applicable law or a...
class Solution: def canBeEqual(self, target: list, arr: list) -> bool: return sorted(target) == sorted(arr) if __name__ == '__main__': target = [1, 2, 3, 4] arr = [2, 4, 1, 3] print(f"Input: target = {target}, arr = {arr}") print(f"Output: {Solution().canBeEqual(target, arr)}")
from xarray import Dataset import os import numpy as np import tempfile from urbanspoon import repository, core from urbanspoon.tests.conftest import ( time_series_factory, spatial_gcm_factory, ) def test_read_dataset(): url = "memory://test_read_dataset.zarr" # writing in memory FS -- don't assign same ...
import os, signal, subprocess, sys import StringIO import ShUtil import Test import Util import platform import tempfile class InternalShellError(Exception): def __init__(self, command, message): self.command = command self.message = message kIsWindows = platform.system() == 'Windows' # Don't u...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random def flip(image): return torch.flip(image, [3]) def contrast(image): return image * (1.0 + random.uniform(-0.2, 0.2)) def brightness(image): return image * (1.0 + random.uniform(-0.2, 0.2)) def ga...
import cv2, time import pandas as pd import numpy as np from math import atan2, tan, radians from pick_gt_px import get_args def make_point(target_pixel, px, v_center, h_center, v_fov, h_fov): v, h = target_pixel v_angle = atan2(v_center - v, v_center / tan(v_fov)) h_angle = atan2(h - h_center, h_center...
import os, sys sys.path.append('../general') sys.path.append('../neuromorphic') from threadhandler import * from neuromorphic import * from tactileboard import * from collections import deque from iLimb import * ilimb = iLimbController('COM16') ilimb.connect() ilimb.control(['thumb','index','middle','ring','l...
from __future__ import unicode_literals from ..permissions import ( permission_document_version_revert, permission_document_version_view, ) from .base import GenericDocumentViewTestCase from .literals import TEST_VERSION_COMMENT from .mixins import DocumentVersionTestMixin class DocumentVersionTestCase(Document...