content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ Created on Sat Feb 26 15:13:29 2022 @author: jasy9 """ from .topsis import TOPSIS
# Author: Ackerley Cheng # file encoding: utf-8 def sameList(listA, listB): return (len(listA) == len(listB)) and (set(listA) == set(listB)) def listInListSet(list, listSet): for idx, ls in enumerate(listSet): if sameList(list, ls): return idx return -1 # check if listA is a subset ...
from django import forms from consent.models import Privilege class PrivilegeForm(forms.ModelForm): class Meta: model = Privilege class ConsentForm(forms.Form): consents = forms.ModelMultipleChoiceField(Privilege.objects, widget=forms.CheckboxSelectMultiple, required=False)
import numpy as np from qm_2019_sss_6.NobleGasModel import NobleGasModel from qm_2019_sss_6.scf import scf from qm_2019_sss_6.mp2 import MP2 atomic_coordinates = np.array([[0.0, 0.0, 0.0], [3.0, 4.0, 5.0]]) # Derived from user input number_of_atoms = len(atomic_coordinates) # Argon parameters - these would change for...
#!/usr/bin/env python3 import os import random from collections import namedtuple, defaultdict dir_path = os.path.dirname(os.path.realpath(__file__)) file = open(dir_path + "/input.txt", "r") lines = [l.strip() for l in file.readlines()] """ acc increases or decreases a single global value called the accumulator by...
import os import pytz from tweepy import OAuthHandler, API, TweepError from . import Data from abc import ABC, abstractmethod import datetime def check_if_datetime_offset_aware(date): return date.tzinfo is not None and date.tzinfo.utcoffset(date) is not None class SocialMediaDataFetch(ABC): _start_date =...
import sys import traceback from django.core.management.base import BaseCommand from django.conf import settings from optparse import make_option from cripts.config.config import CRIPTsConfig from cripts.core.mongo_tools import mongo_find_one from cripts.events.event import Event from prep import prep_database cla...
from d20.Manual.Facts import (Fact, registerFact) from d20.Manual.Facts.Fields import StringField @registerFact('hash') class MD5HashFact(Fact): _type_ = 'md5' value = StringField() @registerFact('hash') class SHA1HashFact(Fact): _type_ = 'sha1' value = StringField() ...
"""Module contains the pydvdid package definition. """ from setuptools import setup with open('README.rst') as readme_file: README = readme_file.read() setup( name="pydvdid", version="1.1", description="A pure Python implementation of the Windows API IDvdInfo2::GetDiscID method, as used by Windows...
import pygame from .math_helpers import * def draw(surface, p1,p2, shading_function, section_length,section_offset): #Adapted Bresenham's line algorithm from #http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm x0,y0 = p1 x1,y1 = p2 dx = abs(x1 - x0) dy = abs(y1 - y0) i...
from flask_pyoidc.flask_pyoidc import OIDCAuthentication from tenacity import retry @retry def get_auth(app): auth = OIDCAuthentication( app, issuer=app.config['OIDC_ISSUER'], client_registration_info=app.config['OIDC_CLIENT_CONFIG'], ) return auth
"""Functions to calculate signal-to-noise ratio in four different cases""" import numpy as np from legwork import strain, psd, utils, evol import astropy.units as u __all__ = ['snr_circ_stationary', 'snr_ecc_stationary', 'snr_circ_evolving', 'snr_ecc_evolving'] def snr_circ_stationary(m_c, f_orb, dist, t...
""" QUESTION: This is an interview question asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 ...
#!/usr/bin/env python from setuptools import setup setup(name='dvaclient', version='1.0', description='Deep Video Analytics Client', author='Akshay Bhat', author_email='dvaclient@deepvideoanalytics.com', url='https://www.deepvideoanalytics.com/', packages=['dvaclient'], packa...
from chainer.backends import cuda import numpy as np def mask_to_bbox(mask): """Compute the bounding boxes around the masked regions. This function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as inputs. Args: mask (array): An array whose shape is :math:`(R, H, W)`. ...
from draco.programs import constraints, definitions, generate, hard, helpers def test_has_definitions(): assert len(definitions.program) assert len(definitions.blocks) def test_definitions_has_marktype(): assert "mark_type" in definitions.blocks def test_has_constraints(): assert len(constraints.p...
from wpilib import DigitalInput import robotmap gear_mech_switch = None def init(): """ Initialize switch objects. """ global gear_mech_switch gear_mech_switch = DigitalInput(robotmap.switches.gear_switch_channel)
class Solution: def multiply(self, T, M): a = (T[0][0] * M[0][0] + T[0][1] * M[1][0] + T[0][2] * M[2][0]) b = (T[0][0] * M[0][1] + T[0][1] * M[1][1] + T[0][2] * M[2][1]) c = (T[0][0] * M[0][2] + T[0][1] * M[1][2] + T[0][2] * M[2][2]) d = (T[1][0] * M[0][0] + T[1][1] * M[1][0] + T[1][...
# [START method_one] # [START method_two] def _bar(): return 'Underscores in method names denote helper methods.' # [END method_one] # [END method_two] # [START method_one] def return_one(): return 1 # [END method_one] # [START method_two] def return_two(): return 2 # [END method_two]
class Song: """Class to represent a song Attributes: title (str): The title of the song artist (Artist): An artist object representing the songs creator. duration (int): The duration of the song in seconds. May be zero """ def __init__(self, title, artist, duration=0): ...
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.piratesgui.BarSelectionMenu from direct.gui.DirectGui import * from pandac.PandaModules import * from direct.directnotify import...
import argparse from paz.pipelines import SSD300FAT, SSD300VOC, SSD512COCO, SSD512YCBVideo from paz.backend.camera import VideoPlayer, Camera import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0], True) parser = argparse.ArgumentParser(d...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2013, SRI International # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code ...
import os import urllib.request import zipfile from random import shuffle from math import floor def download_dataset(): print('Beginning dataset download with urllib2') url = "http://cs231n.stanford.edu/tiny-imagenet-200.zip" path = "%s/tiny-imagenet-200.zip" % os.getcwd() urllib.request.urlretrieve(url, path) p...
from behaviors.button import ButtonBehavior, ToggleButtonBehavior from behaviors.touch_effecs import EffectBehavior from kivy.uix.image import Image from kivy.uix.anchorlayout import AnchorLayout from kivy.properties import ( ListProperty, ObjectProperty, ) from kivy.graphics import Color, Rectangle from kivy.c...
import os from sys import argv tobs = int(argv[1]) for i in range(6): if i != 4: for j in range(10): if j==0: os.system('tail -10000 tobs%d/window%d/hb_list_tobs_%d_task_%d.dat > tobs%d/window%d/window%d.dat'%(tobs,i,tobs,j,tobs,i,i)) else: os.system('tail -10000 tobs%d/window%d/hb_l...
from binaryninja import * from binaryninja.binaryview import BinaryView from binaryninja.platform import Platform from .browser import ImagePickerDialog # binja doesn't want to load mods in a plugin's dir # so hopefully we can just hack that in manually # We do this after importing binaryninja, because in my local...
# 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...
import argparse import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from dp_autoencoder import Autoencoder import mimic_dataset import dp_optimizer import sampling import analysis # Deterministic output torch.manual_seed(0) np.random.seed(0) class Generator(nn.Module): ...
# Generated by Django 3.0.1 on 2020-01-06 22:04 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('chat', '0008_message_front_key'), ] operations =...
# the first import can't be removed import scripted_rest_sys_path from dbx2.dbx_logger import logger import splunk, os, json from json import loads from dbx2.simple_rest import SimpleRest from dbx2.java_home_detector import JavaHomeDetector from dbx2.splunk_client.splunk_service_factory import SplunkServiceFactory imp...
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ # a ^ 0 == a # a ^ a == 0 # a ^ b ^ a = a ^ a ^ b = 0 ^ b = b a = 0 for i in nums: a ^= i print(a) return a print(...
# This software is open source software available under the BSD-3 license. # # Copyright (c) 2020 Triad National Security, LLC. All rights reserved. # Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights # reserved. # Copyright (c) 2020 UT-Battelle, LLC. All rights reserved. # # Additional copyright...
from typing import Tuple, Type, List, Dict, Union from pyfileconf.main import PipelineManager, SpecificClassConfigDict def get_pipeline_dict_path_and_specific_class_config_dicts_from_manager(manager: PipelineManager ) -> Tuple[ ...
""" Task-Specific consistency training on downstream task (BreastPathQ) """ import argparse import os import time import random import numpy as np from PIL import Image import cv2 import copy import pingouin as pg import statsmodels.api as sm import pandas as pd from tqdm import tqdm import torch.backends.cudnn as cudn...
from __future__ import absolute_import import datetime from .config import get_config_file_paths from .util import * # config file path GOALS_CONFIG_FILE_PATH = get_config_file_paths()['GOALS_CONFIG_FILE_PATH'] GOALS_CONFIG_FOLDER_PATH = get_folder_path_from_file_path( GOALS_CONFIG_FILE_PATH) def strike(text):...
from __future__ import absolute_import import argparse import os import sys # sys.path.append(".") import time import torch from tensorboardX import SummaryWriter from metrics.evaluation import evaluate from metrics.vae_metrics import VaeEvaluator from struct_self.dataset import Dataset from struct_self.dataset impo...
# coding= UTF-8 ### Command line of python <filename> was getting angry till I added the line above. I think ### it needs to know what types of characters to expect (i.e. latin, korean, etc..) import datetime ### I needed to switch to single quotes instead of double. I’m not sure why... name = raw_input('Yo what y...
# -*- coding: utf-8 -*- # type: ignore """Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2019 Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Softw...
""" QLayouted module. """ # ISC License # # Copyright (c) 2020–2022, Paul Wilhelm, M. Sc. <anfrage@paulwilhelm.de> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice app...
#import json def parse(command): #split = json.loads(command) #parsedCommand = split return command def main(): pass if __name__ == "__main__": main()
from happy_bittorrent.algorithms.torrent_manager import *
import pytest import shutil import zipfile from pathlib import Path from squirrel.settings import AddonInstallerSettings from squirrel.addons import ZipAddon from test_addon_install import test_addon_install_path from test_addon_install import test_addon_backup_path from test_addon_install import settings from fixt...
#!/usr/bin/python import csv import hashlib import os import sys idx = 1 IGNORED_DIRECTORIES = {'.git', '.svn'} def walk(version_root, app, version): if type(version) == type(bytes): version = version.decode("utf8") if version in IGNORED_DIRECTORIES: return global idx print('av %d %s...
import logging from pathlib import Path import whoosh from whoosh import qparser from whoosh.filedb.filestore import FileStorage from whoosh.index import EmptyIndexError from whoosh.query import Every from django.conf import settings from mayan.apps.common.utils import any_to_bool, parse_range from mayan.apps.lock_m...
from __future__ import absolute_import # Copyright (c) 2010-2018 openpyxl from collections import defaultdict class BoundDictionary(defaultdict): """ A default dictionary where elements are tightly coupled. The factory method is responsible for binding the parent object to the child. If a reference...
import os import random import numpy as np import pickle as pkl import networkx as nx import scipy.sparse as sp from utils import loadWord2Vec from math import log from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import metrics from sklearn.linear_model import LogisticRegression from sklearn im...
# Clase 4. Curso Píldoras Informáticas. print(5 + 6) print(10 % 3) print(5 ** 3) print(9 / 2) print(9 // 2) Nombre = 5 print(type(Nombre)) Nombre = 5.4 print(type(Nombre)) Nombre = "John" print(type(Nombre)) Mensaje = """ Esto es un mensaje utilizando comilla triple. Sirve para da...
# # @lc app=leetcode.cn id=382 lang=python3 # # [382] 链表随机节点 # # https://leetcode-cn.com/problems/linked-list-random-node/description/ # # algorithms # Medium (57.03%) # Likes: 66 # Dislikes: 0 # Total Accepted: 6K # Total Submissions: 10.6K # Testcase Example: '["Solution","getRandom"]\n[[[1,2,3]],[]]' # # 给定一个...
from setuptools import setup with open("README.md") as f: readme = f.read() with open("LICENSE") as f: license = f.read() setup( name="PERFORM", version=0.1, author="Christopher R. Wentland", author_email="chriswen@umich.edu", url="https://github.com/cwentland0/pyGEMS_1D", description...
class ProxyError(StandardError): def __init__(self, title, message): super(ProxyError, self).__init__() self.title = title self.message = message self.error = "Error" def __str__(self): return "%s => %s:%s" % (self.error, self.title, self.message) class ResourceError(...
__author__ = 'wanghao' # import threading import sys import socket from struct import * import time import threading def run_flow(dst_ip, port, size): def run(dst_ip, port, size): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # data = os.urandom(size) data = pack('c', 'a') ...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch import os # Implementing relu() def relu(z): if z > 0: return z else: retur...
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' # Write your code here def right(a,b): r=a for...
import mykde """ If a font in the browser is not Droid, in Google Chrome right click on the text with the wrong font, select 'Inspect element', find 'Computed style' and 'font-family' in it: font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; And for each font do 'fc=match': $ fc-match Helvetica Liber...
# -*- coding: utf-8 -*- """ Created on Thu May 25 11:25:36 2017 @author: azkei We Briefly covered operations between two data structures last file. We will cover how arithmetic operators apply between two or more structured here using Flexible Arithmetic Methods such as add(), sub(),div(),mul() """ # 1. Flexible Arith...
from django.utils import timezone import pytz class TimeZoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get("time_zone") if tzname: timezone.activate(pytz.timezone(tzname)) el...
from podcast.views import home_page from django.urls import path from . import views app_name = "podcast" urlpatterns = [ path('', views.home_page, name="home-page"), path('podcast/',views.podcast_list, name="podcast-list"), path('podcast/search/',views.search_podcast, name="podcast-search"), path('po...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Pytest configuration.""" from __future__ import absolute_import, print_function ...
import requests from bs4 import BeautifulSoup from .handler import add_handler @add_handler(r'http(s?)://drops.dagstuhl.de/(\w+)') def download(url): metadata = dict() metadata['importer'] = 'drops' data = requests.get(url) soup = BeautifulSoup(data.text, "lxml") authortags = soup.find_all("meta"...
# reference page # https://iric-solver-dev-manual-jp.readthedocs.io/ja/latest/06/03_reference.html import sys import iric import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import LightSource from scipy import signal, interpolate import flow class cgns(): def __in...
from django.urls import path from . import views urlpatterns = [ path('',views.index, name='homePage'), path('profile/<username>/', views.profile, name='profile'), path('profile/<username>/update', views.edit_profile, name='update'), path('category/<category>/', views.category, name='category'), pa...
""" Leetcode #300 """ from typing import List import bisect class Solution: def lengthOfLIS(self, nums: List[int]) -> int: inc = [float("inf")] * len(nums) size = 0 for num in nums: i = bisect.bisect_left(inc, num) inc[i] = num size = max(i+1, siz...
import random from multiprocessing import Pool from gym_puyopuyo.agent import tree_search_actions from gym_puyopuyo.state import State def benchmark(depth, threshold, factor): state = State(16, 8, 5, 3, tsu_rules=False) total_reward = 0 for i in range(1000): if i % 100 == 0: print(i, ...
import json import csv import sys from pathlib import Path import datetime import pytest import networkx as nx from sb.aws_trace_analyzer import CSV_FIELDS, extract_trace_breakdown, longest_path, create_span_graph, duration, get_sorted_children, is_async_call, call_stack # noqa: E501 def test_get_sorted_children():...
# -*- coding: utf-8 -*- import math import numpy as np import numpy.random as npr import cv2 # from matplotlib.colors import rgb_to_hsv # from matplotlib.colors import hsv_to_rgb from configure import cfg import utils.blob # from caffe.io import resize_image def GenerateBatchSamples(roi, img_shape): sampled_bbo...
from django.urls import path from .views import ResultListView, create_result, edit_results urlpatterns = [ path("create/", create_result, name="create-result"), path("edit-results/", edit_results, name="edit-results"), path("view/all", ResultListView.as_view(), name="view-results"), ]
""" Class for manipulating user information. """ from datetime import date, timedelta from functools import total_ordering from logging import getLogger from os import stat from os.path import exists from re import compile as re_compile from stat import (S_IMODE, S_ISDIR, S_ISREG) from typing import ( Any, Collecti...
import os import setuptools with open("README.md") as f: long_description = f.read() with open( os.path.join(os.path.dirname(__file__), "config", "requirements", "base.txt") ) as f: requirements = [i.strip() for i in f] setuptools.setup( name="rembrain_robot_framework", version="0.1.4", auth...
#coding:utf-8 from flask import Flask, redirect, url_for, request from datetime import datetime from flask_bootstrap import Bootstrap from app.config_default import Config as DefaultConfig bootstrap = Bootstrap() def check_start(app, db): from app.includes.start import _exist_config, exist_table, create_path, se...
""" Generate_branched_alkane ======================== """ from rdkit import Chem import numpy as np import random def generate_branched_alkane(num_atoms: int, save: bool=False) -> Chem.Mol: """Generates a branched alkane. Parameters ---------- num_atoms : int Number of atoms in molecule to be ...
from django.core.exceptions import ValidationError from django.test import TestCase from openwisp_users.models import OrganizationUser, User from .utils import TestOrganizationMixin class TestUsers(TestOrganizationMixin, TestCase): user_model = User def test_create_superuser_email(self): user = User...
from tensorflow_functions import cosine_knn import collections import numpy as np import logging from embedding import load_embedding import operator from sklearn.cluster import KMeans from utils import length_normalize, normalize_questions, normalize_vector, calculate_cosine_simil, perf_measure import sklearn.metrics ...
from Impromptu import *
import pytch from pytch import ( Sprite, Stage, Project, when_green_flag_clicked, when_this_sprite_clicked, ) import random # Click the balloons to pop them and score points class BalloonStage(Stage): Backdrops = [('midnightblue', 'library/images/stage/solid-midnightblue.png')] # TODO: ...
from environment import environment as env class syscalls: """This class holds a framework for system calls and should ultimately depend on an architecture template I think. For now, it's basically a function map to allow programming system calls like you really would. """ def __init__(self): ...
from astute.__main__ import main from astute.__main__ import Icon if __name__ == '__main__': main(icon=Icon('astute/astute.ico'))
# *ex2 - Escreve um programa com laço de repetição para o usuario encerra-lo apenas quando desejar, onde seu objetivo será fornecer a nota musical, bem como sua frequencia. bom base na tecla fornecida pelo usuario from os import system from time import sleep from cores import * def sair(): print(f'\t\t{cor["ve...
# coding: utf-8 # libraries import import json from flask import Flask, render_template, redirect, url_for, request, jsonify, flash from flask_zurb_foundation import Foundation from sqlalchemy_wrapper import SQLAlchemy app = Flask(__name__) # Configuration app.config["DEBUG"] = True from models import RandomData,...
class Solution(object): def match_note_to_magazine(self, ransom_note, magazine): if ransom_note is None or magazine is None: raise TypeError('ransom_note or magazine cannot be None') seen_chars = {} for char in magazine: if char in seen_chars: seen_ch...
# File : text.py # Author : Zhengkun Tian # Email : zhengkun.tian@outlook.com import torch import logging from otrans.data import * from torch.utils.data import Dataset class TextDataset(Dataset): def __init__(self, params, datadict, is_eval=False): self.params = params self.is_eval = is_eva...
"""Custom test and setup properties for checkin pull_info provider.""" load("//container:providers.bzl", "PullInfo") def _pull_info_validation_test_impl(ctx): pull_info = ctx.attr.target[PullInfo] compare_script_file = ctx.actions.declare_file("compare.sh") compare_script = """#!/usr/bin/env bash function...
# Converting the main code to use datetime objects as well instead of just time objects # Took out defaults from the iter functions import time, math from datetime import datetime from models.energy import defaultModel, load_data, GPSCoordinate#, powerConsumption from models.Predictor import powerGeneration # function ...
#!/usr/bin/env python3 #ccc 2021 senior 10/15 from sys import stdin from itertools import repeat m = int(stdin.readline()) n = int(stdin.readline()) k = int(stdin.readline()) canvas = [] for _ in range(m): canvas.append(list(repeat(False,n))) gold = 0 for _ in range(k): query = stdin.readline().split() qu...
import requests import json from . import filler, models VALID_HTTP_METHODS = { 'GET': ['url'], 'PATCH': ['url', 'data'], 'PUT': ['url', 'data'], 'POST': ['url', 'data'], 'DELETE': ['url'], } def call(step, responses, config: models.SuiteConfig): """ Main API Caller ...
''' Created on 1.12.2016 @author: Darren '''''' Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples: [2,3,4] , the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a d...
from tkinter import * import sys import os.path sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from search import * import numpy as np distances = {} class TSP_problem(Problem): """ subclass of Problem to define various functions """ def two_opt(self, state): """ Neighbour generatin...
import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import matplotlib.animation as animation from matplotlib.text import OffsetFrom import numpy as np import csv a = [] b = [] with open('curvatest.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: a.ap...
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser(description='Gossip Chat via GPT2') parser.add_argument('-m', '--model', dest="model", help="pretrained model path") parser.add_argument('-c', '--config', dest="config", help="model config path") parser.add_argument('-p', '--port', dest='port', def...
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Employee from django.forms import ModelForm, fields from .models import Order from .models import Customer from .models import Tag from .models import Product ...
from django.http import HttpResponse from django.shortcuts import reverse from django.views import View class HeavenTestAPIView(View): def get(self, request): link_format = "<a href='{reversed_link}'>{link}</a>" example_urls = [link_format.format(reversed_link=reverse(link), link=link) for link i...
""" @author: Gabriele Girelli @contact: gigi.ga90@gmail.com """ import argparse from fastx_barber import scriptio from fastx_barber.const import PATTERN_EXAMPLE, FlagData from fastx_barber.exception import enable_rich_assert from fastx_barber.flag import ( FastqFlagExtractor, FlagStats, get_fastx_flag_extr...
""" Minimal and functional version of CPython's argparse module. """ import sys try: from ucollections import namedtuple except ImportError: from collections import namedtuple class _ArgError(BaseException): pass class _Arg: def __init__(self, names, dest, metavar, arg_type, action, nargs, const, d...
import json from hashlib import sha256 from typing import List from ..configs import BaseLayerConfig def create_dir_name_from_config(config: BaseLayerConfig, prefix: str = "") -> str: config_class_name = config.__class__.__name__ config_json = json.dumps(config.to_dict_without_cache()) return f"{prefix}{...
#!/usr/bin/env python3 # @Time : 27/6/29 2:46 PM # @Author : fangcheng.ji # @FileName: qfl_atss.py import math import torch import torch.nn.functional as F from torch import nn import os from typing import Dict, List from .fcos import Scale from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERAT...
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # 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 require...
#pragma repy # This test tries to do recvmess / stopcomm in a loop def foo(ip,port,mess, ch): print ip,port,mess,ch if callfunc == 'initialize': for x in xrange(0,10): ch = recvmess(getmyip(),<messport>,foo) sleep(.1) stopcomm(ch) sleep(.1)
import os from datetime import timedelta class Config(object): DEBUG = False AUTHENTICATED_SEARCH_API = os.environ['AUTHENTICATED_SEARCH_API'] SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CASES_URL = os.environ['CASES_URL'] MATCHING_URL = os.environ['MATCHING_URL'] OWNERSHIP_URL = os.en...
import gym import random import tensorflow import numpy as np from collections import deque import matplotlib.pyplot as plt import utils.utils as utils import tensorflow as tf from ddpg_tf import DDPG env = gym.make('BipedalWalker-v2') env.seed(0) sess = tf.Session() agent = DDPG('ddpg', utils.load_args(), sess=sess)...
from factory import robot import rospy from std_msgs.msg import Float64 from std_msgs.msg import Bool from geometry_msgs.msg import Point import time as t import math as m t0=t.time() Robot=None class rosact(object): def __init__(self): rospy.init_node('act') self.pubs=[] self.pubs.append(...