content
stringlengths
5
1.05M
from enum import Enum import configparser import constants as c class Server(str, Enum): NA = 'americas' EU = 'europe' ASIA = 'asia' SEA = 'sea' class Setting(): def __init__(self): self.config = configparser.ConfigParser() self.port = c.PORT_IP # self.config.read('config...
LOG_LOCATION = '/opt/log/road_collisions/road_collisions.log'
import os, sys import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging import csv from slicer.util import VTKObservationMixin import platform import time import urllib import shutil from CommonUtilities import * from packaging import version def _setSectionResizeMode(head...
""" Support for Neato Connected Vaccums sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.neato/ """ import logging import requests from homeassistant.helpers.entity import Entity from homeassistant.components.neato import ( NEATO_ROBOTS...
import os import datetime from friends_analyzis import * #import codecs s = "fb_id:\nmail:\nplec:\nimie:\nnazwisko:\ndata_urodzenia_fb:\ndata_urodzenia_znana:\nnumer_tel:\nmiasto_urodzenia:\nmiejsce_zamieszkania:\nzwiazek:\nnauka:\nprofile_img_src:\n" def person_in_base(fbid): #if there is no person i base f = o...
import json import requests class ScyllaREST(): def __init__(self, ip='127.0.0.1', port=10000): self.ip = ip self.port = port self.url = 'http://{}:{}'.format(ip, port) self.headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', ...
from events import * import os from events import * from localisation import * from ideologies import * from countries import * class mod_file(game_object): def __init__(self, directory): self.directory = directory self.event_files_dict = {} self.ideology_dict = {} self.country_dic...
# Cyclical figurate numbers # Problem 61 # Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are # generated by the following formulae: # Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... # Square P4,n=n2 1, 4, 9, 16, 25, ... # Pentagonal P5,n=n(3...
#coding:UTF-8 import discord from datetime import datetime from discord.ext import tasks import os TOKEN = os.environ['DISCORD_BOT_TOKEN'] CHANNEL_ID = 874242284844122172 #チャンネルID # 接続に必要なオブジェクトを生成 client = discord.Client() # 60秒に一回ループ @tasks.loop(seconds=60) async def loop(): # 現在の時刻 now = datetime.now().str...
try: from unittest.mock import patch except ImportError: # for python 2.7 from mock import patch
from typing import Callable, Dict from ..typing import ASGIFramework from ..utils import invoke_asgi class DispatcherMiddleware: def __init__(self, mounts: Dict[str, ASGIFramework]) -> None: self.mounts = mounts async def __call__(self, scope: dict, receive: Callable, send: Callable) -> None: ...
# proxy module from __future__ import absolute_import from mayavi.scripts.util import *
import pytest from computer.adders import half_adder, full_adder, ripple_carry_adder @pytest.mark.parametrize( "a, b, sum, carry", [ ("0", "0", "0", "0"), ("0", "1", "1", "0"), ("1", "0", "1", "0"), ("1", "1", "0", "1") ] ) def test_half_adder(a, b, sum, carry): s, c =...
""" Get size of population from width of node """ import math def GetSize(width): if isinstance(width, str): width = float(width) return 100 ** (width/0.3) def GetWidth(size): if isinstance(size, str): size = float(size) return math.log(size, 100) * 0.3 if __name__ == "__main__":...
import os from datetime import datetime import pandas from sklearn.externals import joblib from util.data.data_tools import preprocess_load_data_forec ''' Utility methods to load, clean, select relevant information, and save clean data for load forecasting data ''' def load_uci_load(): load_processed_path = '....
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2019 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
''' A simple explicit position prediction script, this time with actions included. ''' uniform_width = 500 cfg_0 = { 'hidden_depth' : 6, 'hidden' : { 1 : {'num_features' : uniform_width}, 2 : {'num_features' : uniform_width}, 3 : {'num_features' : uniform_width}, 4 : {'num_features' : uniform_width}, 5 : ...
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import json import logging import os import random import tempfile import urlparse import zipfile from tempfile import TemporaryFile impor...
from django.shortcuts import render from django.views.generic import CreateView from django.shortcuts import redirect from django.contrib import messages from .models import Question from .forms import AnswerForm class ReceivedQuestionsView(CreateView): template_name = "question/received_questions.html" def...
''' 9. Write a Python program to list all files in a directory in Python. ''' from os import listdir from os.path import isfile, join list_files = [f for f in listdir('C:\\Users\\fortune\Desktop\Hash Analytics\KPMG\Day6 Tasks Solutions')] print(list_files)
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
from datetime import datetime from enum import Enum, unique from sqlalchemy.dialects.postgresql import UUID from . import db @unique class Permission(Enum): FOLLOW = 1 BLACK = 2 WRITE = 4 MODERATE = 8 ADMIN = 16 class Role(db.Model): __tablename__ = 'roles' id = db.Column(UUID(as_uuid...
class PaymentInitiateFailed(Exception): pass class WalletCreationFailed(Exception): pass class ChannelCreationFailed(Exception): def __init__(self, message, wallet_details=None): super().__init__(message) self.wallet_details = wallet_details def get_wallet_details(self): re...
import pytest from cattr import BaseConverter, Converter @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter]) def test_unstructure_int(benchmark, converter_cls): c = converter_cls() benchmark(c.unstructure, 5) @pytest.mark.parametrize("converter_cls", [BaseConverter, Converter]) def test_...
# write_FBS_activity_set_EIA_CBECS_Land.py (scripts) # !/usr/bin/env python3 # coding=utf-8 """ Write the csv called on in flowbysectormethods yaml files for land use related EIA CBECS """ import flowsa from flowsa.settings import flowbysectoractivitysetspath datasource = 'EIA_CBECS_Land' year = '2012' if __name__ =...
from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import make_pipeline from sklearn.metrics import silhouette_score fr...
from .clip import ClipTab from .compile import CompileTab from .download import DownloadTab from .video import VideoPlayer
# -*- coding:utf-8 -*- """ Created on 8/20/2018 Author: wbq813 (wbq813@foxmail.com) """ class StrUtil: # 字符串是否为空 @staticmethod def is_empty(str_in): return str_in is None or len(StrUtil.trim(str_in)) == 0 # 去除空格和换行符 @staticmethod def trim(str_in): if len(str_in...
import uuid import json from flask.ext.redis import FlaskRedis db = FlaskRedis() class BadFieldException(BaseException): pass class NotFoundException(BaseException): pass class TTLDBaseModel(object): __key_pattern__ = 'nothing' __fields__ = [] __blacklist__ = ['_meta'] _doc = {} de...
"""View managment for account and main pages.""" from django.conf import settings from django.contrib.auth import login as auth_login from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models...
# MIT License # # Copyright (c) 2019 Tskit Developers # # 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, me...
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import random import string import logging # Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import skipIf, TestCase from tests.s...
import os import numpy as np from lonia.utils import get_config_yaml, normalize, normalize_df __mapping__ = { 'macro_news': 'MACRO_NEWS', 'international_news': 'INTERNATIONAL_NEWS', 'stock_market': 'VN_STOCK_MARKET', 'banking': 'BANKING', 'oil_and_gas': 'OIL_AND_GAS' } class TFRanking(object)...
from flask_restful import Resource from flask import request, make_response from app.common.exceptions import StatusCodeException from app.common.auth import auth class Token(Resource): ENDPOINT = '/auth/token' def post(self): try: email = request.data.get('email', None) pass...
from utils.EarthQuake import EarthQuake from utils.weiboHS import getWeiboHotSearch from WechatBot.plugins.ToolsManager import ToolsManager from apscheduler.schedulers.background import BackgroundScheduler from .BaiduSignin import BaiduSignIn import logging class AutoLaunch(object): def __init__(self, **utilities)...
"""Minimal test that our parameter derivation logic does what we expect. """ import struct from hypothesis import given import hypothesis.strategies as st from Crypto.Cipher import Salsa20 from umash import C, FFI @given( bits=st.integers(min_value=0, max_value=2 ** 64 - 1), key=st.none() | st.binary(min_size...
# -*- coding: utf-8 -*- import sys from UI.element import Element from IO import Terminal class Button(Element): """A usable Button for user interface Arguments: Element {UI.element.Element} -- An Element """ def __init__(self, position, label, name="", alignement="left"): """Crea...
from typing import Dict, List from django.contrib.auth import get_user_model from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string User = get_user_model() def send_html_to_email( to_list: List, subject: str, template_nam...
import os import unittest import unittest.mock from programy.bot import Bot from programy.clients.polling.twitter.client import TwitterBotClient from programy.clients.polling.twitter.config import TwitterConfiguration from programy.storage.config import FileStorageConfiguration from programy.storage.factory import Sto...
import random from enum import Enum from math import factorial from threading import Thread OFFSETS = [ (0, -1), (1, 0), (0, 1), (-1, 0), ] SOLUTION_COUNTER = 0 RNG = random.Random() DEFAULT_BOARD_WIDTH = 15 DEFAULT_BOARD_HEIGHT = 7 POINTS_PER_COLUMN = [5, 3, 3, 3, 2, 2, 2, 1, 2, 2, 2, 3, 3, 3, 5] ...
import os import errno from shutil import copyfile # os crawler output_root = '../output' target = 'to_here' for path, directory, files in os.walk('../scaffolder/default_folder'): # path = root.split(os.sep) print(path, directory, files) root_directory = path.split('/', 3)[-1] print('root directory:...
from flask import Flask, request, jsonify from flask_cors import CORS from tensorflow import keras import numpy as np import math model = keras.models.load_model('../kulo_model') app = Flask(__name__) CORS(app) # https://www.raspberrypi.org/forums/viewtopic.php?t=149371#p982264 def valmap(value, istart, istop, ostart...
""" Find more at: https://github.com/l-farrell/isam-ob/settings """ import logging import uuid from pyisam.util.model import DataObject from pyisam.util.restclient import RESTClient NET_INTERFACES = "/net/ifaces" logger = logging.getLogger(__name__) class Interfaces(object): def __init__(self, base_url, use...
class Solution: def thirdMax(self, nums: List[int]) -> int: first, second, third = float('-inf'), float('-inf'), float('-inf') for num in nums: if num > first: first, second, third = num, first, second elif first > num and num > second: second,...
""" Python mapping for the CoreLocation framework. This module does not contain docstrings for the wrapped code, check Apple's documentation for details on how to use these functions and classes. """ import sys import objc import Foundation from CoreLocation import _metadata from CoreLocation._CoreLocation import * ...
""" Copyright (c) 2013-2014, Christine Dodrill All rights reserved. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, inclu...
from torchvision import datasets, transforms from base import BaseDataLoader from typing import Optional import torch from .wrapped_datasets import CIFAR10WithIndex, CIFAR100WithIndex import os import numpy as np import math class MnistDataLoader(BaseDataLoader): """ MNIST data loading demo using BaseDataLoade...
#!/usr/bin/env python import os import sys from collections import defaultdict from goatools import obo_parser def make_go_term_dict(obo): go_terms = obo_parser.OBOReader(sys.argv[1]) go_term_dict = {} for go in go_terms: go_term_dict[go.id] = go.name if go.alt_ids: for id in g...
""" ASGI config for main project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import g...
import logging import os import requests from dotenv import load_dotenv logger = logging.getLogger('logger_main') logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) def create_workspace(trello_apikey, trello_token, wrksp_name): url = ...
from heapq import merge import math import os import time import sys #Uncomment this if the script will run within AEDT with Ironpython. Setup the path where pyaedt folder is. #path_to_pyaedt_root_folder="" #sys.path.append(path_to_pyaedt_root_folder) from pyaedt import Edb, Hfss3dLayout, is_ironpython from pyaedt.g...
# python Higher-order function print '************** Higher-order function Test Programs **************' print abs f = abs print f print f(-1) def add(x,y,f): return f(x) + f(y) print add(-1,-9,abs) raw_input()
import graphene from django.apps import apps from wagtail.documents.models import get_document_model from wagtail.images import get_image_model from wagtail.search.backends import get_search_backend from ..registry import registry def SearchQuery(): if registry.class_models: class Search(graphene.Union):...
import os, sys import glob import math import time import numpy as np import torch class UnorderedSeqFileData(object): def __init__(self, data_dir, file_list, bsz, dim, tgt_len, ext_len=None, device='cpu', normalize=True, distributed=False, down_sample=1): self.data_dir ...
#!/usr/bin/env python3 """ Geoscience Australia - Python Geodesy Package Coordinate Module """ from geodepy.constants import Projection, utm, grs80 from geodepy.angles import (DECAngle, HPAngle, GONAngle, DMSAngle, DDMAngle, dec2hpa, dec2gona, dec2dms, dec2ddm, ...
import ast import boto3 import subprocess import sys import csv from io import StringIO from urllib.parse import urlparse import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) LOGGER = l...
# coding=utf-8 # Copyright 2021 The Tensor2Robot 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 applicable ...
#!/usr/bin/python3.7 import os, time, random, threading, json, shutil, sys, ctypes from PIL import Image import stagger import io from pygame import mixer from flask import Flask from pynput.keyboard import Key, Listener import logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Thilak Rathinavelu """ # Standard imports import logging import argparse import sys import os from subprocess import run from functools import partial logger = None home_dir = os.path.expanduser("~") script_dir = sys.path[0] git_config = ("git", "config",...
""" This is an straightforward example of the injectable framework in a single Python file. .. seealso:: For better understanding of this framework you can look at the other examples in the :ref:`usage_examples` section. The :ref:`basic_usage_example` is a good start! """ # sphinx-start from examples import E...
import numpy as np # def is_passable_coordinate(map_layout, coord_z, coord_x): def is_passable_coordinate(grid, z, x): # # Hole on the floor; can't pass # if self.is_passable_object(grid[0, z, x]): # return False # same level or above is passable; then can pass if z >= 0 and x >= 0 and z < gr...
from django.apps import AppConfig class PenerbitConfig(AppConfig): name = 'penerbit'
"""This module contains all the Facebook specific selectors and text. Whenever Facebook modifies their code, this will need to be updated to accomodate the changes. #webscraperlife CSS Selectors have better performance than XPath and should be used in all circumstances UNLESS you cannot select it properly in CSS. For ...
import numpy as np import pandas as pd from matplotlib import pyplot as plt admissions = pd.read_csv('binary.csv') #making dummy variables for ranks data = pd.concat([admissions, pd.get_dummies(admissions['rank'], prefix='rank')], axis=1) data = data.drop('rank',axis=1) #standardizing data for field in ['gre',...
from string import Template import numpy as np from PuzzleLib.Compiler.Codegen.Types import half_t, float_t from PuzzleLib.Cuda.Utils import prod, roundUpDiv minMaxTmpl = Template(""" extern "C" __global__ void minMaxOnRow$ext(int *idx, const $T *mat, int w) { float curMax = $initVal; int curIdx = -1; for (int ...
from django.conf import settings from django.urls import reverse, reverse_lazy from django.views.generic import ListView, UpdateView, DetailView, FormView, CreateView, View from .forms import QuillFieldForm, QuillPostForm from .models import QuillPost __all__ = ( 'QuillPostListView', 'QuillPostCreateView', ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict from fbpmp.pid.service.credential_service.cloud_credential_service import CloudCredentialServi...
''' 剑指 Offer 48. 最长不含重复字符的子字符串 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。   示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 示例 3: 输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。   请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。   提示: s.length <= 4...
import dill as pickle import numpy as np f = open('pickle/point_circle_second_order_safety_layer_gaussian_l2_projection_radial_action_second_order_layer_with_buffer.p', 'rb') d = pickle.load(f) f.close() safety_layer, ppo = d.values() env = ppo.env lb, ub = env.action_space.low, env.action_space.high obs = env.reset(...
from bs4 import BeautifulSoup import requests def get_href_to_list(url): """ Get all the href elements of a URL to a list :param url: URL of the website to extract the href elements :return: list of href elements """ page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser'...
# from os import popen from pathlib import Path from qbay.models import * import subprocess # Set the current folder current_folder = Path(__file__).parent # Creating a user object for frontend testing # of create product functionality register("TestUser", "create_product_test@qbay.com", "Password99...
# -*- coding: utf-8 -*- def main(): from math import sqrt from itertools import combinations n = int(input()) xy = list() for i in range(n): xy.append(tuple(map(int, input().split()))) ans = 0 for point1, point2 in list(combinations(xy, 2)): dist = sqrt(...
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
from .activities import get_activities from .activity import get_activity from .upload import post_upload from .config import set_config from .login import login from .logout import logout from .profile import get_profile from .stats import get_stats
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # -*- encoding: utf-8 -*- # # Copyright (c) 2020 anqi.huang@outlook.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.apach...
import os def makeFilesMap(curr_dir): myMap = {} for root, dirs, files in os.walk(curr_dir, topdown=False): for name in files: if os.path.isfile(os.path.join(root, name)): #print(os.path.join(root, name), "with size:", os.path.getsize(os.path.join(root, name))) ...
#...................Drive a pressure/temperature sensor.................. #Author: James Bramante #Date: May 8, 2017 import ms5837 import threading import time import statistics as stats class SensorDriver(object): def __init__(self, samplerate = 100., density = 997., baseTime = 0.): """ Cons...
apiLoginId = "5KP3u95bQpv" transactionKey = "346HZ32z3fP4hTG2" transactionId = "60163892435" payerId = "LM6NCLZ5RAKBY" customerProfileId = "1929820324" customerPaymentProfileId = "1841987457" customerProfileShippingId = "901056173" amount = "12.23" subscriptionId = "326280" days = 34
"""template_filter_demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home'...
# # PySNMP MIB module ZYXEL-SFLOW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-SFLOW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:45:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
# -*- coding: utf-8 -*- from __future__ import absolute_import def teardown_module(module): from nltk.corpus import wordnet wordnet._unload()
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RIrdisplay(RPackage): """An interface to the rich display capabilities of Jupyter front-e...
"""Hermes MQTT server for Rhasspy ASR using Kaldi""" import gzip import logging import os import threading import typing from collections import defaultdict from dataclasses import dataclass, field from pathlib import Path from queue import Queue import networkx as nx import rhasspynlu from rhasspyasr import Transcrib...
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to t...
import pandas as pd import os import skimage.io as skio from collections import OrderedDict from glob import glob from tqdm import tqdm import argparse def process_dir(input_dir, save_dir, campaign_name, species_filename=None, save_csv=True): # Find all lst files lst_filenames = sorted(glob(os.path.join(input...
"""XMPP/Jabber Client Interface and Support.""" # stdlib import inspect import os import re # Third Party import treq from twisted.web import client as webclient from pyiem.util import utc, LOG from twisted.internet import reactor from twisted.words.xish import domish, xpath from twisted.words.xish.xmlstream import ST...
width = input('Please enter width: ') price_width = 10 item_width = width - price_width header_format = '%-*s%*s' format = '%-*s%*.2f' print '=' * width print header_format % (item_width, 'Item', price_width, 'Price') print '-' * width print format % (item_width, 'Apples', price_width, 0.4) print format % (i...
import numpy as np import re def update_all_tags(closest_roi): if closest_roi['Shape_type'] == 'Rectangle': closest_roi['Tags']['Center tag'] = (int(closest_roi['topLeftX'] + closest_roi['width'] / 2), int(closest_roi['topLeftY'] + closest_roi['height'] / 2)) closest_roi['Tags']['Top left tag'] = (...
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- # from . import glfw from . import freetype try: ...
from training.models.chromosome import Chromosome from training.models.neural_bird import NeuralBird from utils import generate_random_int_range, generate_random_range def test_generate_random_int_range(): result = generate_random_int_range(min_range=0, max_range=100) assert (0 <= result < 100) def test_gen...
import string str=string.ascii_letters #Prime Number def prime(p): if p==1: print('1 is a uniqe number') elif p%2==0: print('Not a Prime Number') elif p%2!=0: for i in range (3,int(p**0.5),2): if p%i==0: print('Not a Prime number') break else: print('Prime number found') #Factorial def fact(n...
"""Create an applet from a Python script. This puts up a dialog asking for a Python source file ('TEXT'). The output is a file with the same name but its ".py" suffix dropped. It is created by copying an applet template and then adding a 'PYC ' resource named __main__ containing the compiled, marshalled script. """ i...
import pytest from aiohttp_pydantic.oas.struct import OpenApiSpec3 def test_info_title(): oas = OpenApiSpec3() assert oas.info.title is None oas.info.title = "Info Title" assert oas.info.title == "Info Title" assert oas.spec == {"info": {"title": "Info Title"}, "openapi": "3.0.0"} def test_info...
# -*- coding: utf-8 -*- # Copyright (c) oct2py developers. # Distributed under the terms of the MIT License. from __future__ import absolute_import, print_function, division import inspect import dis import threading import numpy as np from scipy.io import loadmat, savemat from scipy.io.matlab.mio5 impor...
from __future__ import print_function import py, sys, subprocess currpath = py.path.local(__file__).dirpath() def setup_make(targetname): if sys.platform == 'win32': raise OSError("win32 not supported yet") popen = subprocess.Popen(["make", targetname], cwd=str(currpath), ...
"""Check if the PR has a news item. Put a warning comment if it doesn't. """ import os from github import Github, PullRequest from fnmatch import fnmatch def get_added_files(pr: PullRequest.PullRequest): for file in pr.get_files(): if file.status == "added": yield file.filename def check_ne...
import os import nn from general_ml import model_suite from nn.mlp import train as mlp from nn.sepCnn.train_sepcnn import train_sequence_model as sepcnn from nn.simple_lstm.train_lstm import lstm from load_data import * from predict import * current_path = os.getcwd() accounts_dir = os.path.join(current_path.split("sc...
from datetime import datetime, timedelta from typing import Optional from bson.objectid import ObjectId from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from fastapi.security.oauth2 import OAuth2PasswordRequestForm from pydantic.networks import EmailStr from pymongo....
from random import shuffle import tensorflow as tf from xcenternet.datasets.dataset import Dataset class McodDataset(Dataset): def __init__(self, dataset_path_tr, dataset_path_te, init_lr): self.features = { TfExampleFields.height: tf.io.FixedLenFeature((), dtype=tf.int64, default_value=1), ...
""" Readout compress a graph into a vector """ from typing import List, Optional import tensorflow as tf from m3gnet.config import DataType from m3gnet.graph import Index from m3gnet.utils import ( get_segment_indices_from_n, register, unsorted_segment_fraction, unsorted_segment_softmax, ) from ._cor...