text
stringlengths
3.07k
12.6k
import requests from bs4 import BeautifulSoup from urllib.parse import urljoin, urlparse import hashlib import os import requests_cache import codecs import shutil from mime import mime import urllib3 urllib3.disable_warnings() requests_cache.install_cache() DOMAINS = ["www.mathplanet.com", ""] LINK_ATTR...
from __future__ import annotations import logging from copy import deepcopy from dataclasses import dataclass, asdict from typing import Dict, Optional, Tuple, List from gutenTAG.anomalies import Anomaly, Position, AnomalyKind, BaseAnomaly from gutenTAG.base_oscillations import BaseOscillation, BaseOscillationInterfa...
import bisect import datetime import functools import math import operator import random from . models import ( City, Company) class CompanyGenerator: """Creates Company objects with a name, industry and seed parameters. Company names are generated from prefix, suffix and often a finalizer part. ...
from itertools import product, tee from math import log from sys import float_info, argv import csv from nltk.data import load from nltk.tag.util import str2tuple from tqdm import tqdm def main(): training_file, model_file = argv[1:4] transition_probabilities, emission_probabilities = train(training_file) ...
## DOCUMENTATION # Documentation of WTForms - https://wtforms.readthedocs.io/en/stable/index.html # PrettyPrinted tutorial on FormFields https://www.youtube.com/watch?v=ymW_HTzVdjc # TIPS: # https://stackoverflow.com/questions/18290142/multiple-forms-in-a-single-page-using-flask-and-wtforms ## WTForms imports from ...
import sys import os COMMAND_SEPARATOR="---\n" NEWLINE="\n" COMMAND_PREFIX=">" SKIP_COLUMN_KEYS=["age", "since", "age", "menu", "ready", "available"] STRING_JOINER=" " def envVarsReady(): if not "FIRST_FILE" in os.environ: print("ERROR: MUST EXPORT FIRST FILE PATH AS `FIRST_FILE`") return False...
#!/usr/local/bin/python3 # # Various functions to test qc.py # import math from qc import * def testSuperdenseCoding(a1, a2): # # Send two classical bits a1 and a2 via superdense coding using entangled qubits A and B # qA, qB = 'A', 'B' clearSystem() b1, b2 = sendSuperdense(a1, a2, qA, qB) assert a1 == b1 and ...
from flask import Blueprint, redirect, jsonify, request, g, make_response, current_app, session from .search import search from .utils import utcnow, get_sha from .models.interests import store_interest from .search_request import SearchRequest from .auth import login_required, handle_authorize import logging logger ...
""" Code defining the models. @author davidrpugh """ import numpy as np import sympy as sym def _haploid_inheritance_probabilities(mutation_rate, incumbent_only): """ R[i,j,k] is offspring genotype i from mother with genotype j and father with genotype k. """ if incumbent_only: R = np.array...
# -*- coding: utf-8 -*- from anytree import Node, RenderTree nodes = [] def verify_node(node): if(node.value == 'programa'): program = node children = list(program.children) while(len(children) > 0): if(children[0].value == 'declaracao'): node = children[0] children = children[1:]...
from typing import List, Optional from fastapi import status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel from starlette.exceptions import HTTPException from pydantic import PydanticValueError class RestErrorDetails(BaseModel): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Collection of helper methods for rdm module @author: baihan """ from typing import Union, List, Dict import numpy as np from scipy.spatial.distance import squareform def batch_to_vectors(x): """converts a *stack* of RDMs in vector or matrix form into vector for...
#! /usr/bin/env python # -*- coding:utf-8 -*- # Author: <NAME>(<EMAIL>) <NAME> # flow lib for visualize the optical flow import numpy as np import matplotlib.colors as cl import matplotlib.pyplot as plt from io import read_flow from img import flow_to_image import cv2 UNKNOWN_FLOW_THRESH = 1e7 SMALLFLOW = 0.0 LARGEFLO...
# Tutorial by www.pylessons.com # Tutorial written for - Tensorflow 1.15, Keras 2.2.4 import os import random import gym import numpy as np from collections import deque import tensorflow from tensorflow.keras.models import Model, load_model from tensorflow.keras.layers import Input, Dense from tensorflow.keras.optimi...
import os # from extune.settings import EXPERIMENTS_DIR, MODULE_DIR from extune.sacred.utils import config_logger # from extune.model import model_fn, train_fn, input_fn from extune.sacred.ingredients import data_ingredient from network.train_network import train_network # from network.config import Config from ten...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import os import random import vizhash from robohash import Robohash import json from PIL import Image try: from .logogram import logogram except: from logogram import logogram try: from .deck import deck except: from deck import deck from flask impor...
from copy import deepcopy from datetime import datetime import reports from reports.executive_fullfilment_requests.entrypoint import ( _generate_bar_charts_from_data, _get_request_count_group_by_type, _get_requests, generate, Part, ) def test_get_requests( mocker, ): parameters = { ...
import os import sys import re def writeCloseLabel(outputScript, postString): outputScript.write(' return\n') outputScript.write('\n') for i in range(0, len(postString)): if (postString[i] != ''): outputScript.write(postString[i]) outputScript.write(' return\n\n') ...
import json import logging from os import getenv from typing import Dict, List from datetime import datetime, timedelta from terrasnek.api import TFC from .run import TFRun, parse_tf_runs logger = logging.getLogger(__name__) ORG = 'org' WORKSPACE = 'workspace' TERRAFORM_SECTION = 'terraform' TERRAFORM_URL = 'url' T...
import sys from typing import List, Callable, Protocol import pandas as pd import streamlit as st import seaborn as sns import sympy import matplotlib.pyplot as plt import numpy as np sys.path.append('') sys.path.append('../../..') from src.common.segment import Segment from src.common.streamlit import function_inp...
#-*- coding:utf-8 -*- import sys, os import json import requests url = 'http://127.0.0.1:5000/' server_url = 'http://172.16.17.32:5001/' # 0 -> 地主上家; 1 -> 地主; 2 -> 地主下家 payload1 = { 'role_id': 0, 'last_taken': { 0: [], 1: [], 2: [], }, 'cur_cards':[], # 无需保持顺序 'history': {...
#Command script for Crypta # Possible commands: # -e Encrypt # -d Decrypt # --help Open help menu # # Example command (Run from cmd line) # python3 crypta.py -e hello there this is a secret code # # If no arguments are supplied then it brings up an interactive cli view # See --help for m...
""" Copyright 2014 Rackspace 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 dist...
# Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # 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 th...
### BlackJack Game ### from random import shuffle # Firstly, create suits, ranks and values of cards suits = ('Hearts', 'Spades', 'Diamonds', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Queen', 'Jack', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Si...
from collections import defaultdict import csv from dataclasses import dataclass, field from datetime import datetime import dateutil.parser from json import dumps import pytz import statistics # Class to record temperature statistics for a particular hour @dataclass class HourStats: indoor_temps: list = field(de...
# -*- coding: utf-8 -*- # Usage: # 1. clone lcddriver from https://github.com/the-raspberry-pi-guy/lcd/ # 2. modified for my LCD1602 address 0x3f (default is 0x2f) # 3. put this file in # 4. connect LCD to 40-pin GPIO: GND - PIN.9, Vcc - PIN.4, SCL - PIN.5, SDA - PIN.3 # 5. connect to network, easiest way is via on-bo...
""" This module contains all the "backend" functions which are used to perform backend tasks such as: - Retrieve data from databases - Transform backend data for frontend usage """ # Import modules from typing import Union, Dict, Optional import os import pandas as pd import json import sys # Get path of the current d...
import argparse import os from glob import glob import imageio import ome_zarr import ome_zarr.scale import ome_zarr.writer import zarr from tqdm import tqdm def get_axes_and_trafos(mip, axis_names, units, resolution): axes = [] for ax in axis_names: axis = {"name": ax, "type": "channel" if ax == "c"...
def install(job): service = job.service prefab = service.executor.prefab if 'redis' not in service.producers: raise j.exceptions.AYSNotFound("Can't find redis service in producers.") # configure redis connection for AYS redis = service.producers['redis'][0] # this line create the defau...
import tensorflow as tf import tflib as lib import tflib.ops.linear import tflib.ops.conv1d import tflib.ops.gru_cell import tflib.ops.embedding def ResBlock(name, inputs, dim): output = inputs output = tf.nn.relu(output) output = lib.ops.conv1d.Conv1D(name+'.1', dim, dim, 5, output) output = tf.nn.rel...
#!/usr/bin/env python3 # This file is part of Krest, and is distributed under the OSI-approved BSD # 3-Clause License. See top-level LICENSE file or # https://github.com/Kitware/krest/blob/master/LICENSE for details. import io import os.path import re import subprocess import sys copyright_notice = \ r"""This file ...
import inspect from abc import ABC, abstractmethod from datetime import datetime from time import sleep import cfscrape import requests import blockapi cfscrape.DEFAULT_CIPHERS += ':!SHA' class Service(ABC): """General class for handling blockchain API services.""" active = True base_url = None r...
import logging import re import pandas as pd from gensim.parsing.preprocessing import strip_numeric, strip_punctuation, strip_tags, strip_multiple_whitespaces, strip_short, remove_stopwords def format_ts(df, time_cols = ["latest_reply","thread_ts", "ts"], unit_time = "s", ...
from logging import Logger import os import time import re import praw import prawcore from model import Database, MessageText, User, Flair, PlayByPost, Nsfw, Location, Identity, OneShot, AgeLimit, Vtt from service import init_logger from text import parse_timezone, parse_day, parse_game, game_abbreviation_to_string,...
# -*- coding: utf-8 -*- from numpy import asarray, atleast_2d, arange, sin, sqrt, prod, sum, round from .go_benchmark import Benchmark class Katsuura(Benchmark): r""" Katsuura objective function. This class defines the Katsuura [1]_ global optimization problem. This is a multimodal minimization prob...
import os import re import sys from collections import defaultdict import django sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'slavdict.settings') django.setup() from slavdict.dictionary.models import Entry from slavdict.dictionary.utils...
# -*- coding: utf-8 -*- from flask import Flask, render_template, abort from os import listdir, rename, mkdir, chown, utime from os.path import isdir, isfile, join import pwd import grp from subprocess import call import json from utils.file_utils import * from shutil import copy, copytree, rmtree class AppDefiniti...
from graphviz import Digraph from octopus.core.edge \ import (EDGE_UNCONDITIONAL, EDGE_CONDITIONAL_TRUE, EDGE_CONDITIONAL_FALSE, EDGE_FALLTHROUGH, EDGE_CALL) def insert_edges_to_graph(graph, edges, call=False): # remove duplicate edges edges = list(set(edges)) # create link b...
import json import logging import os import werkzeug from werkzeug import serving import guild.app import guild.project_util import guild.view # Manually setup package level access for consistent API usage werkzeug.serving = serving DEFAULT_MAX_EPOCHS = 400 #########################################################...
from machine import UART import utime from machine import Pin class M5310_A(): def send_cmd(self,cmd): self.uart.write(cmd + '\r\n') def cheak_ack(self,buf, ack): if ack in buf: return True else: return False def __init__(self): self.rst = Pin(18, Pin...
"""Console script for deeprenewal.""" import random import os import numpy as np import mxnet as mx from pathlib import Path from tqdm.autonotebook import tqdm def seed_everything(): random.seed(42) np.random.seed(42) mx.random.seed(42) seed_everything() from gluonts.trainer import Trainer from gluonts....
from xdnlp.word_discover.ngram import Ngrams from xdnlp.utils import logging_run_time, read_lines from xdnlp.utils import default_logger as logging from collections import Counter from tqdm import tqdm import os import time import math settings = { "ngram": "ngram.pic", "corpus_name": "corpus.txt", "char_v...
""" Verify the domain against the list of most popular domains from OpenDNS (https://github.com/opendns/public-domain-lists). Let's see how useful it is to prevent phishing domains. """ from enum import Enum import json import logging import re import tldextract import ahocorasick import wordsegment from .base import...
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. MLM datasets """ import random import torch from torch.nn.utils.rnn import pad_sequence from toolz.sandbox import unzip from .data import (DetectFeatTxtTokDataset, TxtTokLmdb, pad_tensors, get_gather_index) def random_word(...
import random from bitstring import BitArray DEBUG = True def debug(stuff): if DEBUG is True: print(stuff) class Gene(object): def __init__(self, word=16, count=0, randomise=True, mutator=0.1): # Representation values # Size of a data word self.__word = word ...
import socket import pickle import select from object import Object """ Main server for running the game Attributes ========== HEADERSIZE: int Max amount of characters for the header to be added to the msg PORT: int The port number to connect too MAX_PLAYERS: int The maximum number of clients that can be ...
from django.db import models from django.contrib.auth.models import User from phonenumber_field.modelfields import PhoneNumberField class RaceChoice(models.Model): race_string = models.CharField(max_length=50) def __str__(self): return self.race_string # Application class, to attach to applicant cl...
from os.path import join as opj import numpy as np from pandas import DataFrame, read_sql_query import matplotlib.pylab as plt from matplotlib import cm as mcmap from matplotlib.ticker import MaxNLocator from configs.nucleus_style_defaults import Interrater as ir from interrater.interrater_utils import _connect_to_anc...
from app import db, app from flask_sqlalchemy import BaseQuery, inspect from sqlalchemy.exc import SQLAlchemyError import time, math import pandas as pd from app.util import TaskStatus class SerializableMixin(object): def serialize(self, include={}, exclude=[], only=[]): serialized = {} for key i...
# -*- coding: utf-8 -*- # @Time : 2020/6/16 23:51 # @Author : zonas.wang # @Email : <EMAIL> # @File : inference.py import math import os import os.path as osp import time import tensorflow as tf import cv2 import numpy as np import pyclipper from shapely.geometry import Polygon from tqdm import tqdm from bac...
""" Provides helper methods and templates for generating cloud config for running containers. """ from functools import partial import base64 import os import requests import logging import urllib2 from jinja2 import FileSystemLoader, Environment, StrictUndefined logger = logging.getLogger(__name__) ETCD_DISCOVERY_...
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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...
import argparse import sys from copy import copy from os import makedirs from os.path import basename, dirname, exists from os.path import join as joinp from typing import List, Sequence import jinja2 from jinja2 import Environment, FileSystemLoader from ros_translator.library import Message, PostProcessors, RosLibrar...
#!/usr/bin/env python3 import censys.ipv4 import sqlite3 import pandas as pd import censys.export import requests c = censys.ipv4.CensysIPv4(api_id="XXXXXXX", api_secret="<KEY>") fields = ["autonomous_system.name", "443.https.tls.certificate.parsed.subject.organization", "ip", "protocols", "autonomous_system.routed_...
import mmcv import torch import torch.nn as nn from .utils import weighted_loss from ..builder import LOSSES @mmcv.jit(derivate=True, coderize=True) # @weighted_loss def kld_loss(pred, target, tao=1.0, nonlinear='sqrt', **kwargs): """KLD loss. Args: pred (torch.Tensor): The prediction. targe...
import argparse import os, sys from typing import Any, List import argcomplete import configparser import string import secrets import re from textwrap import dedent from slugify import slugify from pathlib import Path SBU_CFG = Path.home() / '.config/sharebyurl.ini' ### need some form of configuration file which stor...
import pickle from typing import List, Tuple, Dict, Callable, Optional import matplotlib.pyplot as plt import numpy as np import torch from dair_pll import file_utils from dair_pll.plot_styler import PlotStyler def average(list: List) -> float: return torch.tensor(list).mean().item() tt = lambda x: torch.tens...
# Django Imports from django.conf import settings from django.db import models # HTK Imports from htk.apps.organizations.enums import ( OrganizationMemberRoles, OrganizationTeamMemberRoles, ) from htk.apps.organizations.utils import ( get_model_organization_member, get_organization_member_role_choices,...
import argparse import sys import time import numpy as np from sklearn.decomposition import PCA from sklearn.linear_model import LassoLars from sklearn.model_selection import KFold from sklearn.preprocessing import PolynomialFeatures def linear_regression(args): with open(args.trainfile) as f: train = np...
import numpy as np from qiskit import * from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.extensions import Snapshot from binary_to_unary import binary_to_unary from cpkraus import CPKraus from qubo_circuit import * # %matplotlib inline #TODO: work on the visualization # Unary to binary implem...
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
##Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range ##Last Updated : 19 Oct, 2020 ##Given two integers X and Y, the task is to perform the following operations: ## ##Find all prime numbers in the range [X, Y]. ##Generate all numbers possible by combining every pair o...
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Copyright 2021 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://w...
import requests, json, os from bson import json_util, ObjectId from flask import Flask, render_template, redirect, url_for, request, jsonify from flask_cors import CORS from pymongo import MongoClient from datetime import datetime from db_functions import import_data, initialize_db DB_SERVER = 'mongodb://localhost:2...
import requests from datetime import timedelta, date, datetime import pandas as pd from io import StringIO import boto3 import smtplib import pytz from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email(email_recipient, email_subject, ...
from django.shortcuts import render from django.http import HttpResponse from .models import Visitor, Convener, Meeting from .Extra_Tools import otp as otpa from .Extra_Tools import genrate_access as ga from .Extra_Tools import send_email as se import datetime import base64 from PIL import Image from io import BytesIO ...
import json import multiprocessing as mp import os import time from dataclasses import dataclass from typing import Any, Callable, Dict, Generic, List, Mapping, Optional, Tuple, TypeVar import numpy as np import torch from pytorch_pfn_extras.reporting import report from torch import nn from tqdm import tqdm from mlpr...
from nltk.corpus import wordnet as wn import itertools import re import nltk import SpellCorrect from SpellCorrect import word_ID,remove_punctuation, tokenize_input def Get_Synset(aimlst,inputword): synsets_aim=[] synsets_input=str() for w in aimlst: synsets_aim.append(wn.synsets(w)) ...
import math import random import re # webcolors is apparently dated. # only 138 colors listed but says 140 on # https://www.w3schools.com/colors/colors_names.asp from typing import Text import webcolors from colormath.color_conversions import convert_color from colormath.color_objects import ( sRGBColor, xyYC...
from os import kill import time import signal import atexit import logging from queue import Queue from typing import NoReturn from multiprocessing import Process, Event from multiprocessing import Queue as pQueue from multiprocessing.connection import Connection from AxiFresco.axifresco import Axifresco, Point, json...
""" Iterable validators for array objects only. They provide a way of applying a schema to any given items in an array. """ from notario.exceptions import Invalid, SchemaError from notario.engine import IterableValidator from notario.utils import is_callable, safe_repr, expand_schema, is_schema class BasicIterableVal...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from home.models import WhatTorrent, ReplicaSet class InfoHolderTest(TestCase): fixtures = ['wha...
# Copyright (c) 2021 <NAME>, <NAME> # # MIT License # # 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, merg...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Author : <NAME> # email : <EMAIL> # Script Name : 01_csv_to_pg.py # Created : 03 August 2020 # Last Modified : 03 August 2020 # Version : 1.0 # PIP : pip install tqdm peewee psycopg2 psycopg2-binary # RESU...
import numpy as np from matplotlib import pyplot import pandas as pd from astropy.io import fits from astropy import wcs import sys from scipy import linalg as la from scipy.ndimage.filters import gaussian_filter import seaborn as sns def T2S(freq, beam): """ convert brightness temperature to Jy """ c ...
import sqlite3 import random import sys def genderizer(pos): if pos == 2: return(random.choice([2, 3])) if pos == 6: return(random.choice([6, 7])) return(pos) def pick_pos(k): options = [0,1,2,4,5,6] choices = random.sample(options, k=k) return([str(genderizer(choice)) for choice in choices]) ...
#!/usr/bin/env python3 __author__ = 'arnold' import configparser import json import shutil import os import math from PIL import Image import clip # Someday I should let the user specify an input config file on the command line... For now it's all hardcoded in here. def clock_colors(config, section): return (...
from django.db import models from django.contrib.auth import get_user_model from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from core.models import TimeStampedModel, Extensions from mptt.models import MPTTModel, TreeForeignKey from djmoney.models.fields import MoneyField...
import os from sklearn.metrics import accuracy_score import pandas as pd import numpy as np from models import Xgboost from configs import XgbConfig from utils import get_experiment_name, load_label_map from augment import ( plus7rotation, minus7rotation, gaussSample, cutout, upsample, downsam...
from django.shortcuts import render from apis.models import TiLoginUserData2 from django.http import HttpResponse from datetime import datetime import re def login_func(request, **kwargs): if request.session.has_key('id') and request.session['id'] == 'root': return render(request, 'login/profile.html', {'v...
#!/usr/bin/env python3 #run with "python3" instead of "python" that runs Python 2 import sys import codecs import random MAX_MISSES = 8 VERBOSITY = 0 def main(): from optparse import OptionParser usage = "usage: %prog [options] <dictionary> [[--] <solver path> [solver args...]] " parser = OptionParser...
''' Personalize and visualize the disk space usage in the terminal ''' import psutil import platform from .charts import Chart, HorizontalBarChart, Options from tools import ints_to_human_readable from tools import save_to_csv, save_to_json, create_usage_warning class DiskUsage: """ Class to retrieve, o...
import os import cv2 import json import argparse from tqdm import tqdm import xml.etree.ElementTree as ET COCO_DICT = ['images', 'annotations', 'categories'] IMAGES_DICT = ['file_name', 'height', 'width', 'id'] ## {'license': 1, 'file_name': '000000516316.jpg', 'coco_url': '', ## 'height': 480, 'width': 64...
#!/usr/bin/python3 from operator import methodcaller from collections.abc import Sequence import argparse import time import os import requests import warnings import gi gi.require_version('GUPnP', '1.0') gi.require_version('GUPnPAV', '1.0') from gi.repository import GUPnP, GUPnPAV, GLib # noqa: E402 class FileBac...
from __future__ import print_function import forseti2 import configurator import json import lcm import threading import time import random import os import settings import util import LCMNode import requests LCMNode = LCMNode.LCMNode class Schedule(LCMNode): matches_dir = '../matches' def __init__(self, l...
import os from pathlib import Path import json import numpy as np import pandas as pd from sklearn.decomposition import PCA import matplotlib.pyplot as plt import torch import torch.nn as nn import gym import neurogym as ngym device = 'cuda' if torch.cuda.is_available() else 'cpu' def get_modelpath(envid): # M...
from collections import deque import gym import numpy as np from gym import spaces, logger from gym.utils import seeding class SnakeAction(object): LEFT = 0 RIGHT = 1 UP = 2 DOWN = 3 class BoardColor(object): BODY_COLOR = np.array([0, 0, 0], dtype=np.uint8) FOOD_COLOR = np.array([0, 255, 0]...
import utils import numpy as np import os from keras.layers import Input, Conv2D, Conv2DTranspose, Cropping2D, Concatenate, Dropout, Activation, BatchNormalization, ZeroPadding2D, MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D from keras.models import Model, load_model, model_from_json from keras.applications.d...
from distutils.errors import CompileError import pandas as pd from datetime import datetime import os import numpy as np import logging import csv def pad_dict_list(dict_list, padel): lmax = 0 for d in dict_list: for lname in d.keys(): lmax = max(lmax, len(d[lname])) for lname in...
import numpy as np import cv2 from time import time, sleep class RollingGraph: """ Class designed to draw in an OpenCv window, graph of variables evolving with time. The time is not absolute here, but each new call to method 'new_iter' corresponds to a time step. 'new_iter' takes as argumen...
import argparse, sys from pipelines_utils import parameter_utils, utils from pipelines_utils_rdkit import rdkit_utils, mol_utils from rdkit import Chem from . import calc_interactions def execute(suppl, writer, report, group_by_field, score_field, score_descending, stats_fields): count = 0 total = 0 err...
from collections import OrderedDict from mido import MidiFile def _parse_horizontal_edges(graph, track, trackid=0): """ Parse a series of horizontal (monophonic) MIDI events into a directed graph structure. They are stored thus: { id1: [(id2, pitch_delta, time_delta)...], ...
#!/usr/bin/python import argparse, sys, os, random, json, zlib, base64, gzip from shutil import rmtree from multiprocessing import cpu_count from tempfile import mkdtemp, gettempdir from Bio.Format.Sam import BAMFile from Bio.Format.Fasta import FastaData from collections import Counter from Bio.Errors import ErrorProf...
""" Author : <NAME> Android Permission Extraction and Database Creation 26 Sept. 2019 """ from os import system as sys import os, time import xml.etree.ElementTree as ET import numpy as np import csv # FUNCTION TO MERGE FOUND PERMISSIONS TO DEFAULT PERMISSION LIST TO CREATE COMPRIHENSIVE PERMISSION LIST def PermLis...
from gpiozero.pins.mock import MockTriggerPin, MockPWMPin, MockChargingPin, MockSPIDevice from .overrides import MockFactory from PIL import ImageTk, Image from time import sleep, perf_counter from os import path class TkDevice(): _images = {} def __init__(self, root, x, y, name): self._root = root ...
import os import tarfile import zipfile from typing import * try: import rarfile # rarfile.PATH_SEP = '/' except ImportError: # pragma: no cover rarfile = None __all__ = [ 'make_dir_archive', 'Extractor', 'TarExtractor', 'ZipExtractor', 'RarExtractor', ] TAR_FILE_EXTENSIONS = ('.tar', ...
import numpy from PyQt5.QtGui import QPalette, QColor, QFont from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import gui as oasysgui from oasys.widgets import congruence from orangecontrib.wise2.util.wise_objects import WiseData from orangecontrib.wise2.widgets.gui.ow_wise_wi...
import random import copy from abc import ABCMeta, abstractmethod from typing import TypeVar, Generic, List from jmetal.component.density_estimator import CrowdingDistance, DensityEstimator from jmetal.component.comparator import Comparator, DominanceComparator, EqualSolutionsComparator, \ SolutionAttributeCompara...
from sqlalchemy import func, or_, and_ from doll.db import * from enum import Enum import argparse import unicodedata import string from sqlalchemy.sql.functions import ReturnTypeFromArgs class unaccent(ReturnTypeFromArgs): pass session = Connection.session class ParseOption(Enum): strict = 1, non_stri...