content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
from numpy import array, arange, float32, uint8
from numpy.random import rand
import os
import sys
import time
from BVchunker import *
from BVchunker.ND2Reader import ReadFromND2Vid
from BVchu... | python |
"""Tests for the models of the careers app."""
from django.test import TestCase
from django.utils.text import slugify
from mixer.backend.django import mixer
class CareerPositionTestCase(TestCase):
"""Tests for the ``CareerPosition`` model."""
longMessage = True
def test_model(self):
instance = m... | python |
import json
from app.main.model.database import User
from sanic.log import logger
from bson import ObjectId, json_util
from ..service.blacklist_service import save_token
from ..util.response import *
class Auth:
@staticmethod
async def login_user(data):
try:
# fetch the user data
... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Hamilton Kibbe <ham@hamiltonkib.be>
import pytest
from ..gerber_statements import *
from ..cam import FileSettings
def test_Statement_smoketest():
stmt = Statement("Test")
assert stmt.type == "Test"
stmt.to_metric()
assert "units=metric" in st... | python |
import torch.nn as nn
import torch.nn.functional as F
import curves
__all__ = ['WideResNet28x10']
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv3x3curve(in_planes, out_planes, fix_points, stride=1):
return... | python |
import numpy as np
from sklearn.preprocessing import RobustScaler
def normalize(_A, mask=None, norm_0mean=False):
"""Norm A (MRI-T2): filtering top 0.1% values by assigning them to the top_thr (the value at the 99th percentage)
then map values to [0 1] range by dividing by the max intensity within the prostat... | python |
"""
data:{coauthorship, coauthor}
dataset:{cora, citeseer, pubmed}
"""
problem = 'coauthorship'
dataset = 'cora'
datasetroot = '../data/' + problem + '/' + dataset + '/'
"""
Configuration of the Network
num_class = {cora: 7, citeseer: }
"""
hidden_dim = 400
out_dim = 200
num_class = 7
"""
For training
"""
update_rat... | python |
import torch
import torch.nn.functional as F
from torch.distributions import Categorical
import numpy as np
from Gym.models.QLearningBase import QLearningBase
class QLearning(QLearningBase):
def __init__(
self,
device,
n_actions,
n_features,
learning_rate=0.01,
gam... | python |
'''
Author: jianzhnie
Date: 2021-12-28 10:13:05
LastEditTime: 2021-12-28 10:20:24
LastEditors: jianzhnie
Description:
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Optimizer
KD_loss = nn.KLDivLoss(reduce='mean')
def kd_step(teacher: nn.Module, student: nn.Module, te... | python |
import pandas as pd
import os
input = __import__('sys').stdin.readline
raw_data = []
for _ in range(44):
tmp = ["", ""]
tmp[0] = float(input())
tmp[1] = input().strip()
raw_data.append(tmp)
for x in raw_data:
print(x)
print(len(raw_data))
try:
dir_path = os.path.abspath(__file__) + "/data/... | python |
import pathlib
import argparse
import shutil
import pytest
import numpy as np
from PIL import Image
from src import image_averager
@pytest.fixture
def test_image_dir(tmpdir):
test_images = pathlib.Path(__file__).parent / 'data' / 'test_images'
target = pathlib.Path(tmpdir) / 'images'
shutil.copytree(te... | python |
from errors import *
from parse import *
from nodes import *
from func import *
from loop import *
from ifelse import *
class FlatNode(object):
pass
class Code(FlatNode):
def __init__(self, words):
self.words = words
class GoTo(FlatNode):
def __init__(self, index):
self.index = index
class Branch(FlatNode):... | python |
# Generated by Django 3.0.4 on 2020-03-17 17:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logomaker', '0002_category_image'),
]
operations = [
migrations.CreateModel(
name='logo',
fields=[
(... | python |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... | python |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, emperor development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.md, distributed with this software.
# ------------------------------------------------... | python |
rounds = ['chicken', 'ribs', 'pork', 'brisket']
class Table:
def __init__(self, id=1, limit=6):
self.id = id
self.limit = limit
self.boxes = {
'chicken': [],
'ribs': [],
'pork': [],
'brisket': [],
}
def add_box(self, round, box):... | python |
import json
import time
import urllib.parse
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
class PaulusHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.... | python |
import cPickle as pickle
import zlib
""" Compressed version of pickle """
def zdumps(obj, compression_level = 3):
return zlib.compress(pickle.dumps(obj,pickle.HIGHEST_PROTOCOL),compression_level)
def zloads(zstr):
return pickle.loads(zlib.decompress(zstr))
def dump(obj,path):
compr = zdumps(obj)
with... | python |
from .pointnet2_head import PointNet2Head
__all__ = ['PointNet2Head']
| python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: ts=4 sts=4 sw=4 tw=79 sta et
"""%prog [options]
Python source code - @todo
This implements the code to store and save data about tweets
IMPORTANT NOTE: All times are in UTC. They must be either naive and represent
UTC or contain valid tzinfo.
"""
__author__ = 'Pa... | python |
"""Includes methods that plays the game. i.e. Self play, and AI v. AI.
Author(s): Jonah Chen, Muhammad Ahsan Kaleem
"""
from time import perf_counter
from copy import deepcopy
from concurrent.futures import ProcessPoolExecutor
from os import mkdir
import numpy as np
import tensorflow as tf
from mcts import optimize... | python |
# Copyright (c) Johns Hopkins University and its affiliates.
# This source code is licensed under the Apache 2 license found in the
# LICENSE file in the root directory of this source tree.
__author__ = "Max Fleming, Darius Irani"
__copyright__ = "Copyright 2020, Johns Hopkins University"
__credits__ = ["Max Fleming"]... | python |
import json
from redisgears import getMyHashTag as hashtag
from rgsync.common import *
class CqlConnection:
def __init__(self, user, password, db, keyspace):
self._user = user
self._password = password
self._db = db
self._keyspace = keyspace
@property
def user(self):
... | python |
from graphics import *
from menu import *
from levels import *
import common as var
import states
from game import *
import lives as l
from pathlib import *
from file import *
from highscores import *
def main():
win = GraphWin("Arkasquash by Alexandre Valente", 800, 800, autoflush=False) #, autoflush=True
sta... | python |
# Released under the MIT License. See LICENSE for details.
#
"""Provide top level UI related functionality."""
from __future__ import annotations
import os
import weakref
from dataclasses import dataclass
from typing import TYPE_CHECKING, cast, Type
import _ba
from ba._generated.enums import TimeType
from ba._genera... | python |
from typing import Sequence, Union, Dict
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from kyle.util import safe_accuracy_score
class EvalStats:
TOP_CLASS_LABEL = "top_class"
"""
Class for computing evaluation statistics of classifiers, including calib... | python |
import subprocess
import os
from pathlib import Path
import glob
os.remove('text.txt')
os.system('E:/ChromeCacheView.exe /scomma D:/Studies/nsfw_test/text.txt')
fo = open("text.txt", "r")
while True:
line = fo.readline()
if not line: break
data=line.split(",",2)
if "data_2... | python |
"""
Global Template Variables
"""
# Standard Library
import os
# Local Library
from app.modules.entity.option_entity import OptionEntity
def globals(request):
option_entity = OptionEntity()
return {
"google_account": option_entity.get_value_by_key("google_analytics_account", ""),
"app_time... | python |
# get rid of this for python2.6+
import imp, sys, os
def imp_path():
cwd = os.path.realpath('.')
return [path for path in sys.path if os.path.realpath(path) != cwd]
try:
json = imp.load_module('json', *imp.find_module('json', imp_path()))
loads, dumps = json.loads, json.dumps
except ImportError:
t... | python |
from enum import Enum
class Trend(Enum):
NONE = 0
DoubleUp = 1
SingleUp = 2
FortyFiveUp = 3
Flat = 4
FortyFiveDown = 5
SingleDown = 6
DoubleDown = 7
NotComputable = 8
RateOutOfRange = 9
| python |
"""
this is a practice file
"""
import math
math.floor(3.4)
| python |
import tensorflow as tf
def loss_fn(y_true, y_pred):
return tf.reduce_mean(tf.keras.losses.categorical_crossentropy(y_true, y_pred))
def accuracy_fn(y_true, y_pred):
y_true = tf.cast(tf.argmax(y_true, axis=-1), tf.float32)
y_pred = tf.cast(tf.argmax(y_pred, axis=-1), tf.float32)
compare = tf.cast(tf... | python |
import django
from django.conf import settings
def pytest_configure():
settings.configure(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
],
ROOT_URLCONF='djangoapp.urls',
STATIC_URL='/static/',
LANGUAGE_CODE='en',
SIT... | python |
#!/usr/bin/env python
from matplotlib import pyplot as pp
import numpy as np
import sys
def levenstein(source, target):
if len(source) < len(target):
return levenstein(target, source)
if len(target) == 0:
return len(source)
source = np.array(tuple(source))
target = np.array(tuple(targ... | python |
__all__ = [
'q1_collections_counter',
'q2_defaultdict_tutorial',
'q3_py_collections_namedtuple',
'q4_py_collections_ordereddict',
'q5_word_order',
'q6_py_collections_deque',
'q7_most_commons',
'q8_piling_up',
]
| python |
"""
Utility functions for plotting figures consistently across different parts of the project
"""
import matplotlib.pyplot as plt
def set_font_size():
"""
Function which sets a standardized font size for all figures. Call this prior to plotting
to apply the standard
"""
SMALLER_SIZE = 10
MED_S... | python |
"""
Status of the API.
"""
from flask import request
from flask_restful import Resource
class Working(Resource):
"""
Working reveals whether or not connection to API is working.
"""
def get(self):
"""
/working/
Args:
xx
Returns... | python |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2016, ARM Limited and contributors.
#
# 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
#
# ... | python |
from __future__ import absolute_import, division, print_function, unicode_literals
from typing import List
import tempfile
from io import StringIO
import pandas as pd
from Bio import AlignIO, SeqIO, Phylo
from Bio.Align import MultipleSeqAlignment
from Bio.Align.Applications import ClustalOmegaCommandline
from .Alig... | python |
import sys
def input():
return sys.stdin.readline()[:-1]
N, M = map(int, input().split())
tree = [[] for i in range(N)]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
tree[a].append(b)
tree[b].append(a)
ans = [[] for i in range(N)]
for target_no in range(N):
for t_fri... | python |
import asyncio
import re
from functools import partial
import pytest
from dagster import (
AssetKey,
AssetMaterialization,
AssetObservation,
DynamicOut,
DynamicOutput,
DynamicOutputDefinition,
ExpectationResult,
Failure,
Field,
In,
InputDefinition,
Materialization,
... | python |
from pytest import approx
from CompAero.FannoFlowRelations import FannoFlowRelations as ffr
from CompAero.internal import FlowState as FS
class TestFannoClassFuncs:
gamma = 1.4
# Test the Functions for Subsonic Case
#######################################################################################
... | python |
import json, os, copy
def tag_check(resourceTags, include=True):
checkTags = json.loads(os.environ['checkTags'])
tagResults = copy.copy(checkTags)
if include == True:
for cTag in checkTags:
for rTag in resourceTags:
#Check each check Tag where there is both a key and val... | python |
import itertools
def get_output_filename(input_filename):
return input_filename.replace('input', 'output')
class Checksum:
day = 2
test = 2
def get_input_filename(self):
return "day" + str(self.day).zfill(2) + ".input"
def process(self, raw_input):
input_spreadsh... | python |
from typing import Iterable, List
from .syntax import Field, NodeType, Syntax
from .node import Node
class CField(Field):
PATH = "path"
NAME = "name"
VALUE = "value"
PARAMETERS = "parameters"
directive = "directive"
argument = "argument"
OPERATOR = "operator"
FUNCTION = "function"
A... | python |
#from __future__ import unicode_literals
from twisted.internet import reactor, endpoints
from twisted.internet.defer import inlineCallbacks
from ..transit_server import Transit
class ServerBase:
log_requests = False
@inlineCallbacks
def setUp(self):
self._lp = None
if self.log_requests:
... | python |
#execute(object)
#object will be the python code
a = "print('hiii')"
print(exec(a))
| python |
# -*- coding: utf-8 -*-
"""Walker that performs simple name-binding analysis as it traverses the AST"""
import ast
from .util import merge_dicts
from .walkers import Walker
from . import compat
__all__ = ['Scoped']
@Walker
def find_names(tree, collect, stop, **kw):
if isinstance(tree, (ast.Attribute, ast.Subs... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: train.py
import argparse
import itertools
import numpy as np
import os
import cv2
import six
import shutil
assert six.PY3, "FasterRCNN requires Python 3!"
import tensorflow as tf
import tqdm
import tensorpack.utils.viz as tpviz
from tensorpack import *
from tenso... | python |
import csv
import matplotlib.pyplot as plt
import numpy as np
def MC_size_dependence():
f = open("./size_dep.csv", 'r')
x = csv.reader(f)
size_MC = []
times = []
for i in x:
size_MC.append(int(i[0]))
times.append(int(i[1]))
fig = plt.figure()
plt.plot(size_MC, times)
plt... | python |
# Copyright 2021 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.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/lice... | python |
#!/bin/python
##
subnetMask = input('Enter your subnet mask in dotted-decimal notation: ')
o1 = int(subnetMask.split('.')[0])
o2 = int(subnetMask.split('.')[1])
o3 = int(subnetMask.split('.')[2])
o4 = int(subnetMask.split('.')[3])
print('Your subnet mask in binary is: {0:08b}.{1:08b}.{2:08b}.{3:08b}'.format(o1, o2, ... | python |
import time
import numpy as np
import cv2
import open3d as o3d
from numba import njit, prange
import pycuda.autoinit
import pycuda.driver as cuda
from pycuda import gpuarray
from matplotlib import pyplot as plt
from pf_pose_estimation.tsdf_lib import TSDFVolume
from pf_pose_estimation.cuda_kernels import source_modul... | python |
import re
import os
import requests
from xml.dom.minidom import (
parseString,
parse as parseFile,
Text as TextNode,
)
from ...conventions import LOCAL_PATH
from .. import readers
class DNFRepositoryMetalink:
def __init__(self, baseurl, repo, architecture):
self.baseurl = baseurl
self... | python |
# Generated by Django 3.1.5 on 2021-07-11 17:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_initial'),
('classroom', '0001_initial'),
]
operations = [
migrations.AlterField(
... | python |
# Licensed to the Apache Software Foundation (ASF) 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 u... | python |
from django.http import JsonResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from django_cookie_app import models
from... | python |
import os
import re
import numpy as np
import pandas as pd
FILE_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
source = os.path.join(FILE_ROOT_PATH, '9889.xlsx')
output = os.path.join(FILE_ROOT_PATH, 'result_9889.xlsx')
def merge_sheets(path: str) -> pd.DataFrame:
'''将每个表格的sheet页中日期、期货成交汇总、期货持仓汇总聚集到一起
... | python |
from ligeor import TwoGaussianModel as TwoG
import numpy as np
def test_initialize_filename(filename, data):
model = TwoG(filename=filename, n_downsample=1, delimiter=',')
assert(((model.phases == data[:,0]) & (model.fluxes == data[:,1]) & (model.sigmas == data[:,2])).all())
def test_initialize_data(dat... | python |
"""
小结 - 实例成员与类成员
创建
实例变量在构造函数中:对象.变量名 = 数据
实例方法:
def 方法名(self):
pass
类变量在类中方法外:变量名 = 数据
类方法:
@classmethod
def 方法名(cls):
pass
使用
实例变量:对象.变量名
... | python |
import argparse
import json
import os.path as pth
import sys
from glob import iglob
from typing import Any, Callable, Dict
from typing import MutableMapping as Map
from typing import Optional, Type, Union, cast
from ..core.fp import OneOf
from ..core.io import CiTool, env, error_block
from ..core.issue import Issue
fr... | python |
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
import math
... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 7 13:10:58 2018
@author: Joseph Bell Geoscience Australia
"""
'''
reads a csv file and adds DGGS to it
This is for placeNames
Placenames is from 2018
A query was used to gather basic placename data into a csv
Code fields were converted into their full te... | python |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... | python |
from scapy.all import *
from flpr import FLPR, FLPR_PORT
from ifaces import ifaces
from util import ban_ip
# verify that the last IP in history is the receiver's IP
def ips_flpr_2(pkt):
ip = pkt[IP]
flpr = pkt[FLPR]
print("flipper message received, ID = %s, CTR = %s, LIM = %s" % (flpr.id, flpr.ctr, flpr.... | python |
#!/usr/bin/env python3
from boldui import Oplist, Expr, var, stringify_op, ProtocolServer
from boldui.framework import Clear, Column, Padding, Center, SizedBox, Rectangle, Text, Flexible
def main():
root = Clear(
color=0xff202030,
child=Column([
Padding(
Text(
... | python |
from Services import ApiService
from Services import DBService
import logging
logger = logging.getLogger('Roby')
#This class can be viewd as an AbstractFactory
# for the adapters, because the data source
# can be different
# Registry / Service container of the Classes that
# can adapt to different data sources or ser... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import sys, signal
import tensorflow as tf
import utils as ut
from agent import Agent
from envs import create_env
logger = ut.logging.get_logger()
def train(args, server, cluster, env,... | python |
def sortedSquaredArray(array):
# Write your code here.
sortedSquared=[0 for _ in array]
smallIndex =0
largeIndex=len(array)-1
for idx in reversed(range(len(array))):
if abs(array[smallIndex])>abs(array[largeIndex]):
sortedSquared[idx] = array[smallIndex]*array[smallIndex]
... | python |
import cv2
import os
import scipy as scp
import scipy.misc
import numpy as np
def triangStats(img, noHoles = False, minPercArea = 0.1):
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, imbw = cv2.threshold(imggray, 10, 255, 0)
_, contours, _ = cv2.findContours(imbw, 1, 2)
maxArea = 0;
Ax = ... | python |
# Copyright 2015 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... | python |
# Generated by Django 2.1.7 on 2019-09-20 15:49
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... | python |
import os
import sys
from collections import defaultdict, OrderedDict
from geodata.encoding import safe_decode, safe_encode
from geodata.i18n.unicode_paths import DATA_DIR
from geodata.text.normalize import normalized_tokens, normalize_string
from geodata.text.tokenize import tokenize, token_types
from geodata.text.p... | python |
#!/usr/bin/python3
"""cleaning gentx data
"""
import json
import logging
# ## Preface: python data tools
import pandas as pd
log = logging.getLogger(__name__)
BORING = ['Verified', 'Task Type', 'Event', 'Submission Link']
def main(argv, stdout, cwd):
log.info('versions: %s', dict(pandas=pd.__version__))
[p... | python |
from . import startup
from . import models
from . import services
from fastapi.responses import JSONResponse
import json
import random
app = startup.app
redisDb = startup.redisDb
card_collection = models.CardCollection(startup.source)
@app.get("/decks")
def get_decks():
"""
Returns all deck types
"""
... | python |
import sys
input = lambda: sys.stdin.readline().rstrip()
n, m = map(int, input().split())
s = {input() for _ in range(n)}
l = []
for _ in range(m):
t = input()
if t in s:
s.remove(t)
l.append(t)
l.sort()
print(len(l), *l, sep="\n") | python |
"""
Backward compatible behaviour with a primary key 'Id' and upper-case field names
"""
from django.db import models
class User(models.Model):
username = models.CharField(max_length=80)
last_name = models.CharField(max_length=80)
first_name = models.CharField(max_length=40, null=True, blank=True)
e... | python |
from flask import render_template, jsonify, request, session, redirect
from dataclasses import Test
import forms
from werkzeug.exceptions import HTTPException
def home():
return render_template("home.html")
def error(e):
return render_template("error.html", error_num=e.code if isinstance(e, HTTPException) ... | python |
# Create your models here.
from django.db import models
from Graphic_reporter.models import Image
class Published_Article(models.Model):
slug = models.CharField(max_length=140)
title = models.CharField(max_length=140)
description = models.CharField(max_length=140)
body = models.TextField()
publish... | python |
# -*- coding: utf-8 -*-
"""Setup file for easy installation"""
from os.path import join, dirname
from setuptools import setup
version = __import__('social_auth').__version__
LONG_DESCRIPTION = """
Django Social Auth is an easy to setup social authentication/registration
mechanism for Django projects.
Crafted using ... | python |
from django.urls import path, include
from . import views
urlpatterns = [
# Home Page URLs
path('', views.home, name="home"),
path(r'^logout/$', views.logoutUser, name="logout"),
path('about/', views.about, name="about"),
# Registrations
path('customer-registration/', views.cusRegister,
... | python |
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class VarSet:
@abc.abstractmethod
def var_names(self, model):
pass
class VarSetFromSubH(VarSet):
"""Creates a VarSet from SubH instances specified in a model.
Args:
label (:class:`VarSet`): VarSet instance
model (:class:... | python |
from mmdet.models.necks.fpn import FPN
from .second_fpn import SECONDFPN
from .second_fpn_ran import SECONDFPN_RAN
from .second_fpn_mask import SECONDFPNMASK
__all__ = ['FPN', 'SECONDFPN', 'SECONDFPN_RAN', 'SECONDFPNMASK']
| python |
import time
import datetime as dt
date = {}
date["Future"] = dt.datetime.now() + dt.timedelta(seconds = 10)
if date["Future"] <= dt.datetime.now():
print("Succ\n") | python |
import re
examples1 = {
"2x3x4": 58,
"1x1x10": 43
}
examples2 = {
"2x3x4": 34,
"1x1x10": 14
}
def day2a(test=False):
if test:
inputs = examples
else:
inputs = open("d2.txt", "r").read().strip().split("\n")
real_total = 0
for item in inputs:
wayall = 0
bl, bw, bh = re.match("^([0-9]+)x([0-9]+)x([0-9]+... | python |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import time
from mmdet.datasets import DATASETS
from .base_sot_dataset import BaseSOTDataset
@DATASETS.register_module()
class UAV123Dataset(BaseSOTDataset):
"""UAV123 dataset of single object tracking.
The dataset is only used to test.
"""
... | python |
# -*- coding: utf-8 -*-
informe_temp_atual = float(input("informe a temperatura atual: "))
if (informe_temp_atual > 0) and (informe_temp_atual <= 15):
print ("Muito frio")
elif (informe_temp_atual >= 16) and (informe_temp_atual <= 23):
print ("Frio")
elif (informe_temp_atual >= 24) and (informe_temp_atual <= 26):
... | python |
def merge_sort(arr):
if len(arr) < 2:
return arr
# divide into 2 half
divider = len(arr) // 2
arr1 = merge_sort(arr[0:divider])
arr2 = merge_sort(arr[divider:])
return merge(arr1, arr2)
def merge(arra, arrb):
i = j = 0
merge_list = []
while i < len(arra) and j < len(arrb):
... | python |
def anagrams(word, words):
return [x for x in words if sorted(list(x)) == sorted(list(word))]
| python |
from random import randint
from compara_texto import ComparaTexto
class GeradorStrings():
def nova(self, comprimento):
comp = ComparaTexto()
caracteres = comp.CARACTERES_POSSIVEIS()
resultado = []
for _ in range(comprimento):
aleatorio = randint(0, len(caracteres) - 1)
... | python |
# Copyright (c) 2019 PaddlePaddle Authors. 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 applic... | python |
#!/usr/bin/env python3
# authors: RocaPiedra
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from __future__ import print_function
import subprocess
import glob
import os
import sys
import random
import time
import numpy as np
import cv2
import py... | python |
"""
Copyright (c) 2022 Intel Corporation
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 writin... | python |
# -*- coding: utf-8 -*-
"""CquenceR.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1iywElgfFio7e8VN1yZOemHm8hRV4IJHy
# Clone CquenceR and PatchBundle
"""
!git clone https://github.com/SecureThemAll/PatchBundle.git
!git clone https://github.com... | python |
"""Data Analysis
================
"""
from os.path import exists
import nixio as nix
import numpy as np
import numpy.linalg
from typing import Dict, List, Tuple, Type, Union, Set, Any, Optional, Iterator
import pandas as pd
from collections import defaultdict
from kivy_garden.collider import Collide2DPoly, CollideEll... | python |
#!../env/bin/python
from db_models import db, ColorScheme
# define columns
columns = ['ColorSchemeName', 'NumCategories', 'CriticalValue' ,'CategoryNumber', 'RedValue', 'GreenValue', 'BlueValue', 'SchemeType']
# open file
f = open('../assets/colorbrewer.csv','r')
# generate inserts for each line
for r in f.readline... | python |
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
def f(phi, current_concentrations):
# use simpler variable names
s1 = current_concentrations[0]
s2 = current_concentrations[1]
v0 = 5.0
k1 = 3.0
k2 = 2.0
change_in_s1 = v0 - k1 * s1
change_in_s2 = k1 * s1 - k2*s2
return [chan... | python |
"""Tools that interact with Ilab's REST database."""
import re
import copy
import traceback
from bs4 import BeautifulSoup
from ua_ilab_tools import extract_custom_forms, ilab_api, api_types
ONLY_INT_FIELDS = [
"Concentration_each_sample", "Concentration", "Volume (uL)",
"Initial_Number_Slides_or_Punches_each_s... | python |
__copyright__ = '''
Copyright 2017 the original author or authors.
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 ... | python |
# George Adamson
# 05/19/2020
fhand1 = open('dijkstraRoute_oceanEN_RD_50km_50.txt')
fhand_out = open('dijkstraRoute_oceanEN_RD_50km_50.pg','w')
# Read in Route
lats = []
lons = []
for line in fhand1:
route_data = line.split(',')
lats.append(route_data[1])
lons.append(route_data[2].rstrip())
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.