text
stringlengths
3.07k
12.6k
import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patches import seaborn as sns import pandas as pd import numpy as np import os import math import scipy.optimize as opt from scipy.optimize import curve_fit def __sst(y_no_fitting): """ 计算SST(total sum of squar...
from __future__ import division from yolov3.models import * from utils.utils import * from utils.datasets import * from utils.parse_config import * from my_models import Network, define_yolo, init_yolo import os import time import datetime import argparse import tqdm import numpy as np import matplotlib.pyplot as plt...
import random from dataclasses import dataclass from enum import IntEnum from defaultlist import defaultlist from PIL import Image, ImageDraw with open('input.txt') as f: inp = [int(x) for x in f.read().split(',')] class Colors(IntEnum): BLACK = 0 WHITE = 1 class Direction(IntEnum): LEFT = 0 ...
from abc import ABC, abstractmethod from copy import deepcopy B_TAG_PREFIX = 'b-' I_TAG_PREFIX = 'i-' SCOPE_ATTRIB_SEP = '-' LEVEL_ATTRIB_SEP = '_' SIMPLE_TAG_ATTRIB_NAME = 'tag' def merge_token_tag( merged_structured_document, merged_token, other_structured_document, other_token, source_sc...
from typing import TYPE_CHECKING import graphene_django_optimizer as gql_optimizer from django.db.models import Sum from graphql import GraphQLError from graphql_relay import from_global_id from ...order import OrderStatus from ...product import models from ...search.backends import picker from ..core.enums import Or...
# Copyright 2018 RethinkDB # # 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, so...
# _*_ coding: utf-8 _*_ import wda import numpy as np import cv2 import webbrowser from urllib import parse import requests import datetime import time def cvBytes_to_numpyNdarray(imgBytes): # cutBytesImg = np.ndarray.tobytes(cutImg) img = np.asarray(bytearray(imgBytes), np.uint8) img = cv2.imdecode(img,...
# Copyright 2017 The TensorFlow 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 applica...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ FILE: sample_satellite_download.py DESCRIPTION: This sample demonstrates: - Creating a Farmer and a Boundary - Queuing a satellite data ingestion job, and waiting for its completion - Dowloading the data synchronously/sequent...
# -*- coding: utf-8 -*- """ Methods to generate geospatial points to sample data. @author: <NAME> <<EMAIL>> """ import numpy as np import geopandas as gpd from numba import njit from shapely.geometry import Point, Polygon, MultiPolygon from shapely.errors import TopologicalError from typing import Optional, Union fr...
"""mkdocs-categories-plugin An MkDocs plugin allowing for categorization of pages in your wiki. """ import logging import re import shutil import unicodedata from logging import Logger, getLogger from pathlib import Path from mkdocs.config import config_options from mkdocs.plugins import BasePlugin from mkdocs.struc...
# Copyright (c) 2016 <NAME> # ======================================================================= # Distributed under the MIT License. # (See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT) """extract the groups from the iddfile""" from __future__ import absolute_import from __future_...
import click import os import elasticsearch import sys import csv import re import sh import json import importlib_resources from dotenv import load_dotenv, find_dotenv from loguru import logger from datetime import datetime from dateutil import tz from profanity_power_index.collect_tweets import collect_tweets from ...
import torch from torch import nn # from original centernet paper def neg_loss(pred, gt): ''' Modified focal loss. Exactly the same as CornerNet. Runs faster and costs a little bit more memory Arguments: pred (batch x c x h x w) gt_regr (batch x c x h x w) ''' pred = pred.unsqueeze(1)...
##Text extractor. ##THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ##IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ##FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ##AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTH...
import torch import math def Diou_loss(preds, bbox, eps=1e-7, reduction='mean'): ''' preds:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,] bbox:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,] eps: eps to avoid divide 0 reduction: mean or sum return: diou-loss ''' ix1 = torch.max(preds[:, 0], bbox[:, 0])...
# # Copyright (c) 2019, Neptune Labs Sp. z o.o. # # 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 agr...
import sys import numpy as np import os import logging import torch import torch.nn as nn import torch.nn.functional as F import torchvision from absl import app, flags from easydict import EasyDict import resnet.models.resnet as resnet from cleverhans.future.torch.attacks import fast_gradient_method, projected_gradi...
#encoding: UTF-8 # Copyright (C) 2016 <NAME> # This file is distributed under the terms of the # MIT License. # See the file `License' in the root directory of the present distribution. """ A collection of wrappers for the *matplotlib* functions. .. Note:: All functions return a *matplotlib* which can be modified...
# -*- coding: utf-8 -*- """ Created on Sun Mar 1 18:17:35 2020 @author: yadav """ import argparse import math import time import os import io import nntools import torch import torch.nn as nn from models import LSTNetAttConvDirect import numpy as np; import importlib import matplotlib.pyplot as plt from plot_uti...
#coding=utf-8 from functools import reduce from werkzeug.security import generate_password_hash, check_password_hash __author__ = 'archer' from flask import current_app from flask_sqlalchemy import BaseQuery from itsdangerous import JSONWebSignatureSerializer from . import db, login_manager from flask_login im...
""" python contact_details.py 'Municipal contact detail - 28 April 2016.xlsx' 'muni.csv' 'persons.csv' python -m pdb muni_contacts.py 'Municipal contact detail - 28 April 2016.xlsx' 'muni.csv' 'persons.csv' """ import csv import string import sys import xlrd from urllib.parse import urlparse expected_headings = [ ...
from __future__ import print_function from __future__ import absolute_import from __future__ import division from math import pi from compas.utilities import pairwise from compas.geometry import angle_vectors from compas.geometry import is_ccw_xy __all__ = [ 'network_find_cycles', ] PI2 = 2.0 * pi def netwo...
print('EXERCITIUL 1') # 1.Take two int values from user and print greatest among them def greatest_num(a,b): if a>b: print(a, "is the greatest value") elif b>a: print(b, "is the greatest value") else: print("the two numbers are equal") a = int(input("da primul numar: ")) b = int(inp...
#!/usr/bin/env python import os import re import pygal import json import requests from bson import json_util import logging from pymongo import MongoClient from datetime import datetime from datetime import timedelta logging.basicConfig(filename='{0}weather.log'.format(os.environ['OPENSHIFT_PYTHON_LOG_DIR']), ...
import matplotlib.pyplot as plt import numpy as np import math from shapely import geometry import os # TODO : write to file in xppaut style rather than like this.. or open weak coupling solution c = ['#511845', '#900c3f', '#c70039', '#ff5733'] s = ['-', '--'] flatten = lambda t: [item for sublist in contour1.collec...
from typing import List from typing import Union from lexer import Token from parseTree import * class SFunction: '''Subduce function ''' def __init__(self, scopeStack: 'ScopeStack', func: Union[function, FunctionDefinition]): self.func = func class SList: '''Subduce list ''' def __ini...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Copyright 2017-2019 Airinnova AB and the PyTornado authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
'''可以被 TensorFlow,MXNet,PyTorch 同时使用 ''' import time from IPython import display import numpy as np from matplotlib import pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 def use_svg_display(): """Use the svg format to display a pl...
import pandas as pd import numpy as np import scipy.stats as ss import statsmodels.api as sm import matplotlib.pyplot as plt from tkinter.filedialog import askopenfilename, asksaveasfilename import re import multiprocessing as mp from labtools.plot import plot_calibration_line import random global data data = {} de...
import os.path import sys from warnings import warn try: _console = sys._jy_console _reader = _console.reader except AttributeError: raise ImportError("Cannot access JLine2 setup") try: # jarjar-ed version from org.python.jline.console.history import MemoryHistory except ImportError: # dev ver...
import pageattributes import htmlhandler import random import yarachecker import scoringchecker from yarachecker import rulesInterpretation supportedAlgorithms = ('static heuristics', 'scoring mechanism', 'yara rules') class UnsupportedCheckingAlgorithmException(Exception): pass class YaraRulesPathNotSetExcepti...
''' DNS-related code ''' import time import logging import urllib import ipaddress import cachetools import aiohttp import aiodns from . import stats from . import config from . import memory LOGGER = logging.getLogger(__name__) async def prefetch(url, resolver): with stats.coroutine_state('DNS prefetch'): ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ Input:raw files of T_Rex dataset output:"T_REx_example.json" example: {'docid': 'Q3343462', 'token': ['Nora','Zaïdi','(','Nora','Mebrak','-','Zaïdi','),','born','on','July','6',',','1965','in','Bethoncourt','(','French','département','of', ...
import numpy as np import pytest from simple_neural_network.evolution import Evolution # init random number generator rg = np.random.default_rng() params = Evolution.allowed_hyperparameters def test_init_obj(): generations, pop_size = 5, 10 evo = Evolution(generations=generations, population_size=pop_size)...
# -*- coding: utf-8 -*- """ Functions for fetching annotations (from the internet, if necessary) """ from collections import defaultdict from pathlib import Path import re import shutil from nilearn.datasets.utils import _fetch_file from neuromaps.datasets.utils import (get_data_dir, get_dataset_info, ...
''' Created on 2013-11-27 @author: Nich ''' from collections import defaultdict from Systems.NetworkMessageSystem import NetworkMessage from description.description import ObjectDescriber import description.description_planner as dp from pynlg.lexicon import XMLLexicon import os def walk_tree_bf(starting_node): ...
import re import os import pandas as pd import numpy as np import gc import nltk #nltk.download('stopwords') #nltk.download('punkt') from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import sent_tokenize, word_tokenize from mpids.utils.PandasUtils import get_pandas_version D...
#!/usr/bin/env python # cardinal_pythonlib/sqlalchemy/insert_on_duplicate.py """ =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0...
from enum import Enum import json import logging_util import requests # reference beepscore Remy / TVService.swift # https://github.com/beepscore/Remy/blob/master/Remy/TVService.swift # instantiate at module level, not class level # https://stackoverflow.com/questions/22807972/python-best-practice-in-terms-of-logging...
import numpy as np import pandas as pd import argparse import math import csv from collections import OrderedDict def get_args(): parser = argparse.ArgumentParser(description='Call peaks over CRISPRi screen windows.') parser.add_argument('guide_data',help='Input flow-fish guide count data.') parser.add...
import os from datetime import datetime, timedelta import pytz from flask import current_app, url_for from sqlalchemy import func from notifications_utils.template import SMSMessageTemplate, WithSubjectTemplate, get_html_email_body local_timezone = pytz.timezone(os.getenv("TIMEZONE", "America/Toronto")) def pagina...
import re import torch import torch.nn as nn def decompose_bnn_lstm(encoder): state_dict = encoder.state_dict() input_size = encoder.input_size hidden_size = encoder.hidden_size num_layer = encoder.num_layers bidirectional = encoder.bidirectional model_list = [] for layer_index in ran...
import multiprocessing import datetime import time import websocket from pprint import pprint import loghandler import configparser import csv import sys import cbpro from google.protobuf.json_format import MessageToDict from pymongo import MongoClient logger = loghandler.LogHandler().create_logger("sidebyside") co...
import traceback from abc import ABC from copy import deepcopy from itertools import chain from inspect import getmembers, isroutine from functools import wraps import pyarrow as pa def feature(pyarrow_type=None, is_helper=False, exceptions=None, **type_args): exceptions = exceptions or tuple() exceptions = ...
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
##################################################################### # # wavegen.py # # Copyright (c) 2015, <NAME> # # Released under the MIT License (http://opensource.org/licenses/MIT) # ##################################################################### import numpy as np import wave from audio import * # now,...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. 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...
""" ### **Data Stores** You will need to store artifacts and intermediate results. You cannot simply write these artifacts to the local filesystem, because each command runs in a container with its own filesystem that disappears when the container exits. And, in cloud mode, containers run on different machines, so ther...
# ----------------------------------- # import # ----------------------------------- from .basebox import Box from heifpy.file import BinaryFileReader # ----------------------------------- # define # ----------------------------------- # ----------------------------------- # function # -----------------...
import numpy as np import os import torch import matplotlib.pyplot as plt import matplotlib.colors as mcolors def plot_training_loss(minibatch_losses, num_epochs, averaging_iterations=100, custom_label=''): iter_per_epoch = len(minibatch_losses) // num_epochs plt.figure() ax1 = plt.subplot(1, 1, 1) ...
import warnings from sqlalchemy import Column, Table, exc from sqlalchemy.orm import column_property from sqlalchemy.orm.interfaces import AttributeExtension from sqlalchemy.sql.expression import Alias from sqlalchemy.sql import expression from sqlalchemy.ext.compiler import compiles from sqlalchemy.dialects.postgresq...
# -*- coding:utf8 -*- """Backlog v2 API """ import re import os import shutil import requests import yaml from urllib import unquote import time class Api(object): """docstring for BacklogApi""" def __init__(self, space_id, api_key=None): self.space_id = space_id self.api_key = api_key ...
import pickle import math import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from tqdm.notebook import tqdm import scipy import sklearn sns.set(color_codes=True) import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader, Subset import torch.optim as...
from typing import List import pandas as pd import panel as pn import param import plotly.express as px import plotly.graph_objects as go import tensorflow_model_analysis as tfma from zenml.core.pipelines.training_pipeline import TrainingPipeline from zenml.core.repo.repo import Repository from zenml.utils.enums impo...
############################################################################### # WaterTAP Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laboratory ...
from sklearn.model_selection import train_test_split from imutils import face_utils import matplotlib.pyplot as plt import numpy as np import cv2 import dlib def facial_landmark(image): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") r...
import itertools import re from copy import deepcopy from rangeslicetools import * groupsRx = re.compile(r"([bl])(\d+)") inf = float("inf") def isPowerOf2(n: int): return not (n & (n - 1)) class Level: __slots__ = ("size", "big") def __init__(self, size: int, big: bool): self.size = size self.big = big ...
import glob import os import time import unittest import elasticsearch import nose.tools as nt from elasticsearch.exceptions import ConnectionError from nose.plugins.skip import SkipTest from topik.fileio import TopikProject from topik.fileio.tests import test_data_path # make logging quiet during testing, to keep T...
from types import NoneType import PySimpleGUI as sg import funcoes import webbrowser from classes import acessoSAP # Classe principal da criação do programa class ProgramPainel: def __init__(self): font_str = 'Arial, 12' size_Input = (6,1) sg.change_look_and_feel('DarkGrey4') # Layo...
from sqlalchemy import Column from sqlalchemy import exc from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import select from sqlalchemy import Table from sqlalchemy import text from sqlalchemy.schema import DDL from sqlalchemy.schema import Sequence from sqlalchemy.sql import ClauseElement...
""" Implementations of IDependenciesPrinter """ from dataclasses import asdict, dataclass from enum import Enum from pathlib import Path from subprocess import check_output from sys import stdin, stdout from typing import Dict, Iterable, Iterator, List, Optional, Tuple import yaml from jinja2 import Template from dep...
# Copyright 2021, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
#%% #Problem one nums = [2,7,11,15] target = 9 def twoSum(arr, target): values = {} for ind, val in enumerate(arr): if val in values: values[val].append(ind) else: values[val] = [ind] output = None for key, val in zip(values.keys(), values.values()): if a...
""" @author: <NAME> @ email: <EMAIL> @ Date: 17.05.2020 """ import torch from torch.autograd import Variable as V import torchvision.models as models import skimage.io from torchvision import transforms as trn from torch.nn import functional as F import os import numpy as np import cv2 # function to load exif of image...
#!/usr/bin/env python3 '''AMQ List Downloader This Python 3 module downloads songs from all availble shows on a user's list from Anime Music Quiz's Expand Library. Python dependencies: pyyaml selenium Other dependencies: geckodriver Firefox ffmpeg ''' import argparse import json import os import re imp...
import logging from django.db import IntegrityError from django import forms from django.utils.translation import ugettext as _ from django.contrib.auth import authenticate from dreamauthbackend.opinsys.models import OpinsysAuthProvider, OpinsysAssociation LOG = logging.getLogger(__name__) class PuavoAuthenticati...
""" Unit tests of the mongoengine interface to MongoDB Does not use portal or fractal server interfaces. """ import pytest import qcfractal.interface as portal from qcfractal.storage_sockets.models import Molecule, Result, Options, \ Procedure, OptimizationProcedure, TorsiondriveProcedur...
""" Simple Parallel Model Selection =============================== In this example, we'll demonstrate how to quickly write a hyperparameter tuning script that evaluates a set of hyperparameters in parallel. This script will demonstrate how to use two important parts of the Ray API: using ``ray.remote`` to define rem...
import json import csv import codecs from collections import Counter, namedtuple import numpy as np from correlations import Correlations #from analyzer import SortedThetas SortedThetas = namedtuple('SortedThetas', 'thetas labels histogram correlations') class ComplexDecoder(object): '''Decodes json complex array...
# Copyright (C) 2016 <NAME> <<EMAIL>> # All rights reserved. # This file is part of the Python Automatic Forecasting (PyAF) library and is made available under # the terms of the 3 Clause BSD license import pandas as pd import numpy as np from enum import IntEnum from . import Utils as tsutil class eDatePart(IntEnu...
import magma as m from magma.testing import check_files_equal import logging import pytest import coreir class And2(m.Circuit): name = "And2" io = m.IO(I0=m.In(m.Bit), I1=m.In(m.Bit), O=m.Out(m.Bit)) @pytest.mark.parametrize("target,suffix", [("verilog", "v"), ("coreir", "json")]) d...
""" train_classifier.py -------------------------------------------------- This script takes the cleaned data and creates a machine learning model for later use. """ # Importing necessary libraries import re import ssl import sys import nltk import pandas as pd from sqlalchemy import create_engine # running nltk.dow...
import math import numpy as np import paddle.v2 as paddle import paddle.v2.dataset.conll05 as conll05 import paddle.v2.fluid as fluid word_dict, verb_dict, label_dict = conll05.get_dict() word_dict_len = len(word_dict) label_dict_len = len(label_dict) pred_len = len(verb_dict) mark_dict_len = 2 word_dim = 32 mark_di...
import os import json import numpy as np import matplotlib.pyplot as plt def compute_iou(box_1, box_2): ''' This function takes a pair of bounding boxes and returns intersection-over- union (IoU) of two bounding boxes. ''' yA = max(box_1[0], box_2[0]) xA = max(box_1[1], box_2[1]) yB = min(b...
""" ORM for Brick """ from collections import defaultdict from . import namespaces as ns from sqlalchemy import Column, String, ForeignKey, create_engine from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # TODO: brick:feeds (many-to-...
import einops import keras import keras.layers import keras.metrics import numpy as np import tensorflow as tf from attrdict import AttrDict import models.eval_metrics import models.model_trainer import models.util import tfu import tfu3d from options import FLAGS class Metro(keras.Model): def __init__(self, bac...
from .interpolator import RaveTrajectoryWrapper, SplineInterpolator from .constraint import ( JointAccelerationConstraint, JointVelocityConstraint, DiscretizationType, SecondOrderConstraint, ) from .algorithm import TOPPRA import numpy as np import logging import time logger = logging.getLogger(__name_...
import pycuda.autoinit import pycuda.driver as drv from pycuda.compiler import SourceModule import numpy as np from wave_2d_fd_perf_gpu.propagators import Propagator class VPycuda(Propagator): """PyCUDA implementations.""" def __init__(self, jitfunc1, jitfunc2, fd_d, model, batch_size, pad, dx, ...
""" Quickstart 1. Pip-install the following dependencies: - sqlalchemy - psycopg2 - -e git+https://github.com/kids-first/kf-lib-data-ingest#egg=kf-lib-data-ingest 2. Export the following environmental variables: - KF_WAREHOUSE_DB_URL= - FHIR_USER= - FHIR_PASS= 3. Tunnel to Bastion dev and run. For the detailed ex...
from django.shortcuts import render from django.views.decorators.http import require_http_methods from django.http import HttpResponseNotFound, JsonResponse from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt import bcrypt from project1.api.models import...
# KBaseMetagenomes.AnnotatedMetagenomeAssembly indexer from src.index_runner.es_indexers.indexer_utils import mean, handle_id_to_file from src.utils.config import config import tempfile import json import gzip import shutil import os def _index_ama(features_file_gz_path, data, ama_id, ver_ama_id, tmp_dir, conf): ...
import sys import pymemcache from pymemcache.client.base import Client from pymemcache.exceptions import MemcacheClientError from pymemcache.exceptions import MemcacheIllegalInputError from pymemcache.exceptions import MemcacheServerError from pymemcache.exceptions import MemcacheUnknownCommandError from pymemcache.ex...
import unittest import sys from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import StringIndexer, OneHotEncoderEstimator, VectorAssembler from onnxmltools import convert_sparkml from onnxmltools.convert.sparkml import buildInitialTypesSimple, build...
import os from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import numpy as np import torch from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader from .dataset import InferenceDataset, InferenceDicomDataset, InferencePngDataset, XRayAnomalyDataset, \ ...
import argparse from sys import stdin, stdout, stderr import csv import base64 import os import os.path import datetime import ijson def prepare_args(): parser = argparse.ArgumentParser( description="Tool export PNG files and detection data to CSV.", usage="./credo-user-mapping.py -j export_0_152...
import numpy as np from randnn.topologies.utils import get_connected_components from randnn.topologies.scale_free import get_degree_seq, degree_seq_to_edges, power_law_dist def test_power_law_dist(): min_degree = 1 max_degree = 3 alpha1 = 0.5 alpha2 = 1.5 alpha3 = 2.5 alpha4 = 3.5 assert...
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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 Software Foundation, either version 3 of the # License, or (at your option)...
import signal import sys import textwrap import os from typing import List from gooey.python_bindings.constants import Events from gooey.python_bindings import constants from gooey.gui.util.freeze import getResourcePath from gooey.python_bindings.types import GooeyParams from gooey.util.functional import merge def...
import numpy as np import sys import os import fnmatch import argparse try: import cv2 as cv except ImportError: raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, ' 'configure environment variable PYTHONPATH to "opencv_bu...
"""NFSP agents trained on simplified risk.""" from absl import app from absl import flags from absl import logging import tensorflow.compat.v1 as tf import numpy as np import igraph as ig import cairocffi import random import pyspiel from open_spiel.python import policy from open_spiel.python import rl_environment fr...
import numpy as np import ray ray.shutdown() ray.init() # A : Action Space # S : State Space @ray.remote class VI_worker(object): def __init__(self, list_of_actions, tran_dict, reward_dict, beta, backup_states, true_action_prob=0.8, unknown_value=0): self.backup_states = backup_states ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import re from astropy.table import Table import Quaternion from parse_cm import read_backstop, read_or_list from Chandra.Time import DateTime import hopper def check_characteristics_date(ofls_characteristics_file, ref_date=None): # de_bytetring the...
import unittest from recordclass import litelist import gc import pickle import sys class litelistTest(unittest.TestCase): def test_len(self): a = litelist([]) self.assertEqual(len(a), 0) a = litelist([1]) self.assertEqual(len(a), 1) def test_items(self): a = ...
#!/usr/bin/python # -*- coding:utf-8 -*- import os import os.path import logging import logging.handlers import sqlite3 import tweepy import requests from six.moves.urllib.request import urlretrieve from six.moves.urllib.parse import urlencode DB_FILENAME = 'aladin.db' LOG_FILENAME = 'aladin.log' ALADIN_ITEM_ENDPOI...
#!/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. import json import os from os.path import join as pjoin from os.path import isfile, isdir from parlai.core.params impor...
import statistics import numpy as np import os import json def load_config(): config_file = os.path.abspath(os.path.join(os.curdir, 'config2.json')) with open(config_file, 'r', ) as config_file: config_string = config_file.read() return json.loads(config_string) def solve(graph, labels): "...
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public...
# tests/test_trees.py # # forestry: Python Tree data structures and tools # # Copyright (C) 2019 by <NAME> # # This module is part of `forestry` and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Unit tests for module trees.py""" # Third-party library imports import pytest ...