content
stringlengths
0
894k
type
stringclasses
2 values
from simple_rl.amdp.AMDPPolicyGeneratorClass import AMDPPolicyGenerator #from simple_rl.amdp.abstr_domains.grid_world.AbstractGridWorldStateMapperClass import AbstractGridWorldL1StateMapper from simple_rl.apmdp.AP_MDP.cleanup.CleanupQMDPClass import CleanupQMDP from simple_rl.apmdp.AP_MDP.cleanup.CleanupQStateClas...
python
from osbot_aws.apis.shell.Lambda_Shell import lambda_shell @lambda_shell def run(event, context): return 'testing lambda layer ... '
python
# -*- coding: utf-8 -*- # # Copyright 2018 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 requir...
python
from imutils.video import VideoStream from datetime import datetime import imutils import cv2 import numpy as np import sys import json import os import time import inspect # Configuration from MMM CONFIG = json.loads(sys.argv[1]) # Computer vision lib files needed by OpenCV path_to_file = os.path.dirname(os.path.ab...
python
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by David J Turner (david.turner@sussex.ac.uk) 10/01/2021, 16:51. Copyright (c) David J Turner import numpy as np from astropy.units import Quantity from ...models.misc import power_law from ...
python
def insertion_sort(A): for i in range(len(A)-1): while i >= 0 and A[i+1] < A[i]: A[i], A[i+1] = A[i+1], A[i] i -= 1 return A if __name__ == '__main__': import random arr = [random.randint(1, 10) for _ in range(10)] assert insertion_sort(arr) == sorted(arr) assert...
python
# # The MIT License (MIT) # # Copyright 2018 AT&T Intellectual Property. All other rights reserved. # # 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 l...
python
#https://www.acmicpc.net/problem/2775 testCase = int(input()) for i in range(testCase): list_base = [i for i in range(1, 15)] list_new = [] k = int(input()) n = int(input()) for j in range(k): for l in range(n): if l-1 >= 0: list_new.append(list_new[l-1] + list_...
python
import tornado.ioloop, tornado.web, tornado.websocket, tornado.template import logging, uuid, subprocess, pykka from datetime import datetime from tornado.escape import json_encode, json_decode logger = logging.getLogger(__name__) # container for all current pusher connections connections = {} frontend = {} ...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-03 13:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('democracy', '0004_lengthen_type_field'), ] operations = [ migrations.AlterFi...
python
#encoding=utf-8 # bankfile_psr2000.py # This file is part of PSR Registration Shuffler # # Copyright (C) 2008 - Dennis Schulmeister <dennis -at- ncc-1701a.homelinux.net> # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S...
python
from rest_framework import serializers from .models import EnrollmentSecret, MetaBusinessUnit, Tag class MetaBusinessUnitSerializer(serializers.ModelSerializer): api_enrollment_enabled = serializers.BooleanField(required=False) class Meta: model = MetaBusinessUnit fields = ("id", "name", "api...
python
from discord.ext import commands from discord.utils import get import discord from datetime import datetime from bot import Shiro from util import strfdelta from apis.anilist_api import find_anime_by_id import asyncio class ModsCog(commands.Cog): def __init__(self, bot: Shiro): self.bot = bot @comm...
python
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. ## ## Test weakref ## ## * Since the IronPython GC heavily differs from CPython GC (absence of reference countin...
python
#Done by Lauro Ribeiro (12/02/2021) # Tutorial 7 - Use the Where Clause import sqlite3 #Connect to database conn = sqlite3.connect('customer.db') #Create a cursor c = conn.cursor() #Query the database c.execute("SELECT * FROM customers WHERE email LIKE '%gmail.com'") items = c.fetchall() for item in items: ...
python
import os, sys # Kiny passou aqui XD def restart(): python=sys.executable;os.excl(python, python, *sys.argv) try: import colorama, requests except: os.system('pip install -r requirements.txt');restart() try: from data import ui, numero, cpf, nome, rg, email except Exception as e: print('ARQUIVO CORROMPI...
python
# -*- coding: utf-8 -*- import pytest from wemake_python_styleguide.violations.best_practices import ( YieldInComprehensionViolation, ) from wemake_python_styleguide.visitors.ast.loops import ( WrongComprehensionVisitor, ) list_comprehension = """ def container(): nodes = [{0} for xy in "abc"] """ gener...
python
# ################################################################## # SAMPLE USAGE # ################################################################## if __name__ == '__main__': # #################### # IMPORT # #################### import json import cProfile from .client import deltaClie...
python
from .currency import * from .profile import * from .account import * from .base import * from .transaction import * from .budget import *
python
from kratos import * import kratos as kts def create_port_pkt(data_width, consumer_ports): return PackedStruct(f"port_pkt_{data_width}_{consumer_ports}", [("data", data_width, False), ("port", consumer_ports, False), ("v...
python
from __future__ import division from __future__ import print_function def elink_module(elink_intf, emesh_intf): """ The Adapteva ELink off-chip communication channel. Interfaces: elink_intf: The external link signals emesh_intf: The internal EMesh packet interface """ # keep track ...
python
import os import re import sys from functools import partial from datetime import datetime from jinja2 import Template from traitlets.config.configurable import Configurable from traitlets import Integer, CBool, Unicode, Float, Set, Dict, Unicode from jupyterhub.traitlets import Callable from wtforms import Boolea...
python
import yaml from boardgamegeek import BGGClient def main(user, member_data_file): bgg = BGGClient() with open(member_data_file, "r") as data_file: member_data = yaml.load(data_file) user_data = member_data[user] del member_data[user] user_collection_size = len(user_data) member_scor...
python
# Generated by Django 2.2 on 2020-10-20 18:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0003_librarysubscription_nightshift'), ] operations = [ migrations.AlterField( model_name='librarybranch', ...
python
import mock from util.factory import channel_factory from util.factory import new_podcast_factory from util.factory import requested_podcast_factory from podcast.download import _download_from_url from podcast.download import download_channel from podcast.models import NewStatus from podcast.models import RadioDirecto...
python
import mne import os import numpy as np import pandas as pd #from .kcmodel import scoring_algorithm_kc from ..features.spectral_features import compute_absol_pow_freq_bands from .base import BaseMethods import sys from scipy.signal import find_peaks import pywt import joblib try: wd = sys._MEIPASS except Attribute...
python
import abc import logging import os import re import shutil import subprocess from pathlib import Path import git from halo import Halo from utils.ExecutionContext import TestRunInfo, get_context, get_timeout, has_bonus, is_strict, set_bonus, set_timeout from utils.TerminalColors import TC from utils.Utils import inte...
python
# flake8: noqa from .random_word import RandomWord, NoWordsToChoseFrom, Defaults from .random_sentence import RandomSentence __author__ = "Maxim R." __copyright__ = "Copyright 2020, Wonderwords" __credits__ = ["Maxim R."] __license__ = "MIT" __version__ = "2.2.0" __maintainer__ = "Maxim R." __email__ = "mrmaxguns@gmai...
python
# Wesley Dias (1º Semestre ADS-B), Lista XI # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Exercícios extras # G. verbing # Dada uma string, caso seu comp...
python
#!/usr/bin/env python from setuptools import setup, find_packages __VERSION__ = '5.0.1' setup( name='sanetime_py3', version=__VERSION__, author='prior', author_email='mprior@hubspot.com', maintainer='finkernagel', maintainer_email='finkernagel@imt.uni-marburg.de', packages=find_packages(),...
python
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 换个消除长度差的方式:拼接两链表。 设长-短链表为 C ,短-长链表为 D ,则当 C 走到长短链表交接处时, D 走在长链表中,且与长链表头距离为 长度差; 链接: https://leetcode-cn.com/problems/two-sum/solution/intersection-of-two-linked-lists-shuang-zhi-z...
python
import asyncio import aiopg import psycopg2 from aiopg.transaction import Transaction, IsolationLevel dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1' async def transaction(cur, isolation_level, readonly=False, deferrable=False): transaction = Transaction(cur, isolation_level...
python
for c in input():print(c,(min((abs(ord(c)-ord(v)),v)for v in'aeiou')[1]+((chr(ord(c)+1)if chr(ord(c)+1)not in'aeiou'else chr(ord(c)+2))if c!='z'else'z'))if c not in('aeiou')else'',sep='',end='')
python
__all__ = ( "class_definition", "class_prefixes", "class_specifier", "long_class_specifier", "short_class_specifier", "der_class_specifier", "base_prefix", "enum_list", "enumeration_literal", "composition", "language_specification", "external_function_call", "element_...
python
import numpy as np from pyyolo import BBox from collections import OrderedDict class TrackedObject: def __init__(self, timestamp: int, bbox: BBox): self.initial_timestamp = timestamp self.max_timestamp = timestamp self.nframes = 1 self.max_bbox = bbox self.curr_bbox = bbox ...
python
import pytest, torch, fastai from fastai.gen_doc.doctest import this_tests from fastai.torch_core import * from fastai.layers import * from math import isclose a=[1,2,3] exp=torch.tensor(a) b=[3,6,6] def test_tensor_with_list(): this_tests(tensor) r = tensor(a) assert torch.all(r==exp) def test_tensor_wi...
python
#!/usr/bin/env python2 ########################################################## # # Script: txt2float.py # # Description: Convert GMT text grid files into float # ########################################################## # Basic modules import os import sys import struct from ParseHeader import * class txt2float...
python
# HDM - Heading - Magnetic # Vessel heading in degrees with respect to magnetic north produced by any device or system producing magnetic heading. # $--HDM,x.x,M*hh<CR><LF> # Heading Degrees, magnetic # M = magnetic # Checksum class hdm(): # Constructor def __init__(self): # Switch this on for verbose ...
python
import os from conans import ConanFile, tools class CppnanomsgConan(ConanFile): name = "cppnanomsg" version = "20181216" _commit_id = "a36d44db1827a36bbd3868825c1b82d23f10e491" description = "C++ binding for nanomsg" topics = ("conan", "cppnanomsg", "nanomsg", "binding") url = "https://github....
python
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None` # self.right = None # self.next = None from collections import deque class Solution: # O(n) space # @param root, a tree link node # @return nothing ...
python
# -*- coding: utf-8 -*- # _mod1.py # Module providing the mod1 function # Copyright 2013 Giuseppe Venturini # This file is part of python-deltasigma. # # python-deltasigma is a 1:1 Python replacement of Richard Schreier's # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. # The delta sigma t...
python
from wordsearch.trie import TrieNode import unittest, re def recursive_equal(first, second): """ Return True if the tree rooted by "first" is identical to the tree rooted by "second", i.e. all the nodes and edges are identical. """ first_queue = [first] second_queue = [second] while first_queue and secon...
python
#!/usr/bin/env python import sys import random import importlib def baseline(a): a.sort() return a def test(a): print SORTFUNCSTR, ": ", print a, a = SORTFUNC(a) # check invariant for i in range(1, len(a)): assert a[i] >= a[i-1] print " --> ", print a SORTFUNC =...
python
import folium my_map = folium.Map(location=[40.4059954,49.8661496,],zoom_start=15) folium.TileLayer('mapquestopen',attr='dasd').add_to(my_map) folium.LayerControl().add_to(my_map) my_map.save('templates/map.html')
python
""" -------------------------------------------------------------- Copyright (c) 2017, AIT Austrian Institute of Technology GmbH. All rights reserved. See file PESTO _LICENSE for details. -------------------------------------------------------------- PESTO-client\createClients\createClients.py for 1 user: ...
python
# At : Thu Apr 30 21:04:44 WIB 2020 import os, sys, time print '\x1b[36m ____ _ _ ' print '\x1b[36m | \\ ___ ___ | |_ ___ ___ | |_ ' print '\x1b[36m | | || -_|| _|| . || . ||_ -|| |' print '\x1b[37m |____/ |___||___||___||__,||___||_|_|\x1b[33m v2.0\n \x1b[34m\xe2\x95\x94\xe2\x95...
python
#!/usr/bin/env python3 """ Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at http://www.apache.org/licenses/LICENSE-...
python
global register_count register_count = 0 global register_refs register_refs = {} global register_dims register_dims = {} # a data structure such that: # identity unique upon initialization # can be merged with other registers # can can be an array or not: can specify dimension and slots # TODO: should the R...
python
import numpy as np from scipy import integrate, interpolate import healpy as hp import subprocess import TheoryCL from .. import utils from .. import bessel class SphericalBesselISW(TheoryCL.CosmoLinearGrowth): """Class for computing the ISW using spherical Bessel Transforms from maps of the density contras...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: geoip.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf ...
python
import requests import json import clipboard import time def main(): temp = None try: import tkinter temp = 1 except: temp = 0 if temp == 0: print("No Valid Tkinter installation found. Either tkinter is not installed or tkinter is not supported on this platform.") if temp == 1: try: from tkinter impor...
python
from typing import * import numpy as np from terminaltables import AsciiTable __all__ = ['format_labels_grid'] def format_labels_grid(labels: Sequence[str], n_cols: Optional[int] = None) -> str: labels = list(labels) if not labels: raise ValueError(f'`labels` must not be empty...
python
from .driver import Driver from .mindriver import MinDriver from .timedriver import TimeDriver from .hysteresisdriver import HysteresisDriver
python
#Biblioteca para gerar itens aleatórios import random #Função para achar o menos valor de um vetor desconsiderando o primeiro item que é o nome do produto def menor_valor(v): menor = v[1] loja_indice = 0 for i in range(len(v)-1): if menor > v[i+1]: menor = v[i+1] loja_indice...
python
import cv2 import numpy as np def resize(filename,width,height): image = cv2.imread(filename) cv2.imshow('Original image',image) cv2.waitKey(0) org_height , org_width = image.shape[0:2] print("width: ",org_width) print("height: ",org_height) if org_width >= org_height: new_image = ...
python
try: import simplejson as json except ImportError: import json from .base_file import BaseFilePlugin from ..xnodes import create_xnode, XNode, XDict, XFileError class PluginJson(BaseFilePlugin): def def_extensions(self) -> set: return {'json'} def load(self, content) -> XNode: ...
python
import datetime from django.views.generic import TemplateView from django.views.decorators.cache import never_cache from rest_framework import viewsets, generics, status from rest_framework.response import Response from . import models from . import serializers from rest_framework.permissions import BasePermission, ...
python
import os import pathlib import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import sys import time import random from tensorflow.keras.preprocessing.image import load_img,img_to_array from tensorflow.keras import layers from multiprocessing.dummy import Pool as ThreadPool print('Python version:...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/28 12:39 # @Author : Meta_Chen # @File : sendip.py # @Software: PyCharm # @Target: 以邮件形式发送ip import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from utils.getip import G...
python
from types import SimpleNamespace import re options_render = { "START_FROM": 0, "PATH_MODEL": 'models/hotdog.blend', "DATASET_NAME": 'hotdog_random_exr', "DATAMODEL_NAME": '', # dataset used for training; == %DATASET_NAME% if empty "RESOLUTION": 512, # resolution of resulting renders "ARCH": 'mlnrf_base', #...
python
# -*- coding: utf-8 -*- from django.conf import settings from django import forms from django.contrib import admin from photologue.models import Photo, Gallery, PhotoEffect, PhotoSize, Watermark from photologue.admin import PhotoAdmin as PhotoAdminDefault from photologue.admin import GalleryAdmin as GalleryAdminDefaul...
python
#!/usr/bin/env python # coding: utf-8 # In[1]: import requests import numpy as np from bs4 import BeautifulSoup import itertools import warnings warnings.filterwarnings("ignore") import pandas as pd import re from lxml import html import math import time import sys # In[50]: def inside_get_year(url_): #url =...
python
from urllib import quote_plus from celery.schedules import crontab class HardCoded(object): """Constants used throughout the application. All hard coded settings/data that are not actual/official configuration options for Flask, Celery, or their extensions goes here. """ ADMINS = ['me@me.test'] ...
python
import codecs import csv from django.contrib import admin from django.shortcuts import HttpResponse from django.utils.translation import gettext_lazy as _ from .models import Subscriber @admin.register(Subscriber) class SubscriberAdmin(admin.ModelAdmin): list_display = ('id', 'first_name', 'last_name', 'email', '...
python
# -*- coding: utf-8 -*- # @Date : 2016-01-23 21:40 # @Author : leiyue (mr.leiyue@gmail.com) # @Link : https://leiyue.wordpress.com/ def async(func): from threading import Thread from functools import wraps @wraps(func) def wrapper(*args, **kwargs): thr = Thread(target=func, args=args, ...
python
import os from .utils import safe_makedirs from config import DATA_ROOT RAW = 'raw' PRODUCTS = 'products' CORRECTED = 'corrected' ALL = 'all' FILENAME = 'filename' class Resolver(object): def __init__(self, data_root=None): if data_root is None: data_root = DATA_ROOT self.data_root =...
python
import dataclasses import itertools import time import typing import ratelimit import requests from loguru import logger GameID = typing.NewType("GameID", int) PatchVersion = typing.NewType("PatchVersion", tuple[str, str]) CALLS_PER_SECOND = 1 DEFAULT_RETRY_ATTEMPTS = (0, 1, 2, 5, 10, 30) @dataclasses.dataclass(fr...
python
from django.core.management.base import BaseCommand import requests from datetime import date from dateutil.relativedelta import relativedelta from dateutil.rrule import rrule, DAILY from decimal import Decimal from currency import model_choices as mch from currency.models import Rate class Command(BaseCommand):...
python
from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomerServiceReminderRel(models.Model): # Customer customer = models.ForeignKey('customers.Customer', verbose_name=_("Customer")) # Service service = models.ForeignKey('services.Service', verbose_name=_("Service")) # Rem...
python
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams params = { 'grid.color': 'k', 'grid.linestyle': 'dashdot', 'grid.linewidth': 0.6, 'font.family': 'Linux Biolinum O', 'font.size': 15, 'axes.facecolor': 'white' } rcP...
python
def climbingLeaderboard(ranked, player): ranked = list(set(ranked)) ranked.sort(reverse=True) result = list() rank= len(ranked) - 1 for score in player: while score > ranked[rank] and rank > 0: rank -= 1 if score < ranked[rank]: result.insert(0, rank+2) ...
python
# this file must exist for couchdbkit to sync our design doc # and it's a good place to import signals from . import signals
python
from unittest import TestCase from unittest.case import expectedFailure from gerrit_coverage.condense import condense class TestMissingLinesToComments(TestCase): def test_empty_list(self): self.assertEqual([], condense([])) def test_single_line(self): lines = [('file', 1)] self.as...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Application of easylearn """ def run(): from eslearn.GUI.easylearn_main_run import main main()# Build
python
import cv2 Complete = cv2.imread("Velocity2RGB.png") cv2.cvtColor(Complete, cv2.COLOR_BGR2RGB) b, g, r = cv2.split(Complete) i = 0 v = 0 c = 0 f = open('VelRGBLog.txt','w') while(True): while i <= 7: h = 0 while h <= 15: if h >= 8: x = 82 + 45*h else: ...
python
# Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain ...
python
# credits to @NotThatMF on telegram for chiaki fast api # well i also borrowed the base code from him from pyrogram import Client, filters from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message from .. import BOT_NAME, HELP_DICT, TRIGGERS as trg from ..utils.data_parser imp...
python
#!/usr/bin/env python #-*- coding: utf-8 -*- #This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software. #The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif...
python
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ if n<1: return [] self.result=[] self.cols=set() self.pie=set() self.na=set() self.DFS(n,0,[]) return self._generate_res...
python
# Enter your code for "Degree Distribution" here. import csv degrees = [] students = [] for l in csv.DictReader(open("degrees.csv")): degrees.append(l) for l in csv.DictReader(open("students.csv")): students.append(l) students = sorted(students, key=lambda x: float(x["score"])) students.reverse() print(st...
python
''' Copyright 2022 Airbus SAS 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, software dis...
python
import pytest from my_lib import add_elements def test_wrong_type(): with pytest.raises(TypeError): add_elements([1, 2], 6)
python
import FWCore.ParameterSet.Config as cms # Make one TrackCand for each seeder import FastSimulation.Tracking.TrackCandidateProducer_cfi hltL3TrackCandidateFromL2OIState = FastSimulation.Tracking.TrackCandidateProducer_cfi.trackCandidateProducer.clone( src = cms.InputTag("hltL3TrajSeedOIState"), SplitHits = cms...
python
from y2015.day02 import * def test_part1(): assert part1("2x3x4") == 58 assert part1("1x1x10") == 43 def test_part2(): assert part2("2x3x4") == 34 assert part2("1x1x10") == 14
python
#namedtuple提供了几个有用的属性和方法来处理子类和实例。 # 所有这些内置属性都有一个前缀为下划线(_)的名称, # 在大多数Python程序中按照惯例表示私有属性。对于 namedtuple, # 然而,前缀是为了保护名称从用户提供的属性名称冲突 import collections Person = collections.namedtuple('Person', 'name age') bob = Person(name='Bob', age=30) print('Representation:', bob) print('Fields:', bob._fields) """ output: Represent...
python
#!/usr/bin/python import numpy as np from math import atan2, sin, cos, pi class DiffDriveController(): """ Class used for controlling the robot linear and angular velocity """ def __init__(self, max_speed, max_omega): # TODO for Student: Specify these parameters self.kp= 0.5 #0.3 ...
python
import os import pathlib from glob import glob import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from tensorflow.keras import Sequential from tensorflow.keras.layers import * from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.pre...
python
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # setting up libraries used in the program from __future__ import print_function from dronekit import connect import exceptions import socket import time import sys import os # clear screen os.system("clear") try: # print out the instruction print ("Take RC c...
python
"""Turn objects from the hyperbolic module into matplotlib figures. """ import copy import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Arc, PathPatch, Rectangle from matplotlib.collections import LineCollection, PolyCollection, EllipseCollection from matplotlib.transforms imp...
python
""" Contains all function related to the genetic algorithm itself. E.g. selection, crossover, and mutation. This is called by the main.py module """ import copy import numpy as np import random from neural_network import apply_neuron_constraints def crossover(parents, gen_size): # If anything goes wrong, this f...
python
import argparse from spiderpy import SpiderApi def main(): """Main function.""" parser = argparse.ArgumentParser(description="Run some live tests against the API") parser.add_argument( 'username', type=str, help="Your email address") parser.add_argument( 'password', type=str, ...
python
from django import forms from django.utils.translation import ugettext as _ from django.core.exceptions import ValidationError from django.contrib.auth.models import User from datetimewidget.widgets import DateTimeWidget from .models import Event, Proposal, Activity class CustomDateTimeWidget(DateTimeWidget): d...
python
# -*- coding: utf-8 -*- """ usage: python3 plot_features.py --segment size 10 """ import sys import os sys.path.insert(0, os.path.join(os.path.dirname( os.path.realpath(__file__)), "../")) from Functions import plot_functions as pf from Functions import utils as ut if __name__ == '__main__': segment_size = ut....
python
"""Spotbugs java tool class to detect bugs inside the project""" import re import shlex import xmltodict from eze.core.enums import VulnerabilityType, ToolType, SourceType, Vulnerability from eze.core.tool import ToolMeta, ScanResult from eze.utils.cli import extract_version_from_maven, run_async_cli_command from eze...
python
import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import argparse import keras import numpy as np import pandas as pd from ashrae.utils import ( MODEL_PATH, timer, make_dir, rmsle, load_data, get_validation_months, ) parser = argparse.ArgumentParser(description=...
python
"""介绍numpy的基本知识""" import numpy as np """[[1, 2, 3],[2, 3, 4]]只是列表形式""" # 将列表转换为数组 array = np.array([[1, 2, 3], [2, 3, 4]]) print(array) print('number of dim', array.ndim) # 数组维数 print('shape', array.shape) # 数组的形式 print('size', array.size) # 数组的大小 """ number of dim 2 shape (2, 3) size 6 """
python
# Copyright 2013 Cloudbase Solutions Srl # # 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 ...
python
# Generated by Django 2.2.1 on 2019-06-26 11:23 import django.db.models.deletion from django.conf import settings from django.db import migrations, models import libs.django.db.models.base_model class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(s...
python
# coding: utf-8 import os import sys from importlib import import_module # import local modules from .utils import load_config, build_vocab, Tokenizer BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_MODULE = "classifier" class Classifier(): def __init__(self, args): self.args = args se...
python
import numpy as np import pycircstat import BirdSongToolbox.free_epoch_tools as fet from BirdSongToolbox.import_data import ImportData from BirdSongToolbox.context_hand_labeling import label_focus_context, first_context_func, last_context_func from src.analysis.ml_pipeline_utilities import all_label_instructions i...
python