text
stringlengths
3.07k
12.6k
# start paramatize #import daemon from wmctrl_lib import * import subprocess import traceback import abc import os.path import time import os from multiprocessing import Pool import threading def spawnApp(appname,exec_bash): print("calling spawnApp ==== ") print(isRunning(appname)) if not isRunning(appna...
__author__ = '<NAME>' from collections import OrderedDict from datetime import date, datetime from functools import lru_cache from ipaddress import ip_address from time import time from typing import Dict, Optional, List, Any, cast import aiohttp_jinja2 import monetdblite from aiohttp import web from ballcone import...
from __future__ import annotations from typing import TYPE_CHECKING from abc import abstractmethod from enum import Enum from dataclasses import dataclass from types import SimpleNamespace from contextlib import contextmanager import torch as th from dltk.utils import autocast_cls, grad_scaler from .events import A...
import sys import os import shutil import logging from configobj import ConfigObj from wx.lib.pubsub import pub import photoinfo import file_matcher import settings config = ConfigObj("default.conf", unrepr=True) VIDEOS = config['videos_dir'] class Organizer: """ Main class, finds and moves/copies photos as speci...
"""Basic XML utilities based on minidom - the built in Document Object Model """ import sys from xml.dom import minidom, Node def print_tree(n, indent=0): while n: print(' '*indent, 'Node name: "%s",' % n.nodeName, 'Node type: "%s",' % n.nodeType, 'Node value: "%s...
import argparse import os import datetime from my_net import * import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.multiprocessing as mp from torchvision import datasets, transforms from torch import optim from torch.distributed.optim import DistributedOptimizer from torch....
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2015-09-16 11:28:21 # @Email: <EMAIL> # @Last modified by: etrott # @Last Modified time: 2016-03-08 12:35:42 import pandas as pd import numpy as np import gspread import re from .utils import get_credentials from .gfiles import get_file_id...
#%% # according to this tutorial: https://realpython.com/primer-on-python-decorators/ import functools def my_first_decorator(func): def wrapper(): print("An event before the function is called") func() print("An event after the function is called") return wrapper def say_whee(): ...
from __future__ import division from builtins import object from past.utils import old_div from proteus import * from proteus.default_p import * from proteus.mprans import SW2DCV from proteus.mprans import GN_SW2DCV from proteus.Domain import RectangularDomain import numpy as np from proteus import (Domain, Context, ...
# ============================================================================== # Copyright (c) 2021, Yamagishi Laboratory, National Institute of Informatics # Author: <NAME> # All rights reserved. # ============================================================================== import os import argparse import torch ...
"""Networks Allocation API list(): show the list of networks show(net): show the properties of net register(net): register the given network addresses(net): show addresses of net addresses(net, status='free'): show only free addresses addresses(net, status='used'): show only free addresses ...
# PetitCalc from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt from PyQt5.QtGui import QPalette, QIcon, QFont, QPixmap, QColor class Calculator: def __init__(self): # Create label widget lbl = QLabel('BasicCalc') lbl.setFont(QFont('Forte', 30)) lbl.setStyleSheet('co...
""" TODO: remove this obsolete SVGImporter see https://github.com/SebKuzminsky/pycam/issues/118 Copyright 2010 <NAME> <<EMAIL>> This file is part of PyCAM. PyCAM 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, ...
import os import django_rq from django.contrib.gis.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from rest_framework.reverse import reverse from converters import CONVERTER_CHOICES, converter_settings from converters.boundaries import BBox,...
import pygame, sys from pygame.locals import * WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) DARKGRAY = (169, 169, 169) YELLOW = (222, 178, 0) PINK = (225, 96, 253) BLUE = (0, 0, 255) BROWN = (139, 69, 19) ORANGE = (255, 99, 71) GRAY = (119, 136, 153) LIGHTORANGE = (255, 176, 56) INTE...
from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource import ResourceManagementClient from azure.mgmt.datafactory import DataFactoryManagementClient from azure.mgmt.datafactory.models import * from datetime import datetime, timedelta import time def print_item(group): """Print a...
# -*- coding: utf-8 -*- from os import name, system from time import sleep from smtplib import SMTP_SSL from email.message import EmailMessage from threading import Thread from random import choice if name == 'nt': system("title The Trickster") system("mode 120, 30") def clear(): system("cl...
import datetime from decimal import Decimal from django.contrib.auth.models import User from django.db import models from pytz import utc import time class Exchanges(models.Model): name = models.CharField(max_length=255) info_frozen_key = models.CharField(max_length=31) def __str__(self): return...
import re from enum import Enum from typing import Iterable, List from pygitguardian.models import Match from .text_utils import Line, LineCategory REGEX_PATCH_HEADER = re.compile( r"^(?P<line_content>@@ -(?P<pre_index>\d+),?\d* \+(?P<post_index>\d+),?\d* @@(?: .+)?)" # noqa ) # Source: https://github.com/jon...
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
import os # from django.shortcuts import render import datetime from django.contrib import messages from django.contrib.auth.decorators import login_required from django.forms import inlineformset_factory from django.shortcuts import redirect, render, get_object_or_404 from django.views.generic.list import ListView fro...
import argparse import numpy as np def solve(*args, **kwargs): return None def main(args): print('Solving') print('Input: {0}'.format(args.input)) print('Output: {0}'.format(args.output)) with open(args.input, 'r') as in_file:import argparse import numpy as np import matplotlib.pyplot as plt im...
#!/usr/bin/env python # coding: utf-8 # In[7]: import requests from pprint import pprint from IPython.core.display import display, HTML from markdownify import markdownify as md import json import re import urllib.request from unidecode import unidecode from datetime import datetime # In[8]: IMPO_ENDPOINT='https...
import torch import torch.nn as nn import torch_geometric.nn as geom_nn import torch_geometric.transforms as geom_transforms from typing import Union class GGNNFlatSum(nn.Module): """ Graph level prediction with gated graph recurrent networks """ def __init__(self, input_channels: int, ...
from colorexlib.colorexlib.writers.HTMLWriter import HTMLWriter from colorexlib.colorexlib.common.datastructures import Tile from colorexlib.colorexlib.common.datastructures import HeatMap from colorexlib.colorexlib.common.styling import Theme from colorexlib.colorexlib.common.styling import StyleSheet from Cheetah.Tem...
import sys import base64 import argparse import logging from functools import partial from itertools import cycle, repeat from threading import Thread from time import sleep import json import multiprocessing as mp from queue import Empty import coloredlogs from websocket import create_connection import bigchaindb_b...
# Copyright 2010 New Relic, 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 law or agreed to in writ...
# =============================================================================== # Copyright 2014 <NAME> # # 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/LI...
import itertools from nose.tools import assert_true, assert_equal, assert_raises import cynetworkx as nx from cynetworkx.algorithms import approximation as approx def test_global_node_connectivity(): # Figure 1 chapter on Connectivity G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3...
""" Simulate a connection to the equipment. """ import os import re import random import logging import importlib from .connection import Connection _backtick_regex = re.compile(r'`(.+?)`') class ConnectionDemo(Connection): def __init__(self, record, cls): """Simulate a connection to the equipment. ...
""" Simple Snake game by Husci - created when learning python """ import pygame import random FPS = 7 UP = 1 RIGHT = 2 DOWN = 3 LEFT = 4 class Snake(object): def __init__(self, block_size, width, height, blocks): self.block_size = block_size # size of a block self.width = width # numb...
""" Compare jobs on factory and Nersc """ import argparse import pprint import pandas as pd import logging from decisionengine.framework.modules import Transform CONSUMES = ['job_manifests', 'Nersc_Job_Info'] PRODUCES = ['nersc_factory_jobs_comparison'] class CompareNerscFactoryJobs(Transform.Transform): """ ...
# Python import logging import re # Genie from genie.metaparser.util.exceptions import SchemaEmptyParserError log = logging.getLogger(__name__) def get_cef_repair_path_of_route(device, prefix, vrf="default", address_family="ipv4"): """ Get 'repair path' of route Args: device ('obj'): Device ...
import asyncio import hashlib from typing import Optional, TypedDict, Dict, Tuple from aiohttp.client import ClientSession import aiohttp from result import Ok, Err, Result from ruuvi_decoders import get_decoder STATION_IP = "10.0.0.21" USERNAME = "username" PASSWORD = "password" class SensorPayload(TypedDict): ...
import os, json, argparse import ML_Methods, Image_Tools import pandas as pd from PIL import Image import numpy as np import matplotlib.pyplot as plt #image processor and retrival might be made into a separate module def imaging_processor(dataset, size = 256., tf_aug = False): list_label_images= [] list_images ...
from builtins import zip from builtins import map from astromodels import Model, PointSource, Uniform_prior, Log_uniform_prior from threeML.data_list import DataList from threeML.bayesian.bayesian_analysis import BayesianAnalysis from threeML.minimizer.tutorial_material import Simple, Complex, CustomLikelihoodLike fr...
import heterocl as hcl import numpy as np import math as mt def top_correlation(M, N, epsilon, dtype=hcl.Int(), target=None): hcl.init(dtype) data = hcl.placeholder((N, M), "data") mean = hcl.placeholder((M,), "mean") stddev = hcl.placeholder((M,), "stddev") corr = hcl.placeholder((M, M), "corr")...
import os import dotenv import bottle import re import pytz import subprocess import hashlib import base64 import json import osgeo import datetime import logging import logging.config logging.config.dictConfig({ "version":1, "disable_existing_loggers":False, "handlers":{ "default":{ "c...
import os import multiprocessing import sys import threading import tempfile import time from datetime import timedelta from unittest.mock import MagicMock import pytest import prefect from prefect.utilities.configuration import set_temporary_config from prefect.utilities.executors import Heartbeat, timeout_handler, ...
import dshelper as dsh import numpy as np import os import pandas as pd import sys import time from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, S...
import datetime from unittest.mock import MagicMock from runboat.db import BuildsDb, SortOrder from runboat.github import CommitInfo from runboat.models import Build, BuildInitStatus, BuildStatus, Repo def _make_build( name: str | None = None, *, status: BuildStatus | None = None, init_status: BuildI...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Input queue to feed example when training with Tensorflow """ from multiprocessing import Process, Queue, Event, Value import queue class Counter(object): def __init__(self): self.val = Value('i', 0) def increment(self, n=1): with self.va...
# -*- coding: utf-8 -*- """ backend.index ~~~~~~~~~~~~~ Implements index controller :author: Feei <<EMAIL>> :homepage: https://github.com/wufeifei/cobra :license: MIT, see LICENSE for more details. :copyright: Copyright (c) 2016 Feei. All rights reserved """ import time import opera...
import logging import asyncio import traceback import collections import time class TerminateProcessing(Exception): pass class Element(object): def __init__(self, downstream=None, logger=None): self.logger = logger self.downstream = downstream self.profiler = None def __rshift__...
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from collections import OrderedDict from datetime import timedelt...
import json from io import BytesIO import pycurl from sdcBePy.common.helpers import check_arguments_not_none def get_url(ip, port, protocol): return "%s://%s:%s" % (protocol, ip, port) class SdcBeProxy: BODY_SEPARATOR = "\r\n\r\n" CHARTSET = 'UTF-8' def __init__(self, be_ip, be_port, header, sch...
#TODO: Use SVM trained on WORKER data to predict the meth score of the DRONE. #TODO: Append the list of drone data... #TODO: Do those compare to the Nanopolish predictions? from ML_SVM_Worker import TrainSVMonWorker clf = TrainSVMonWorker() print (clf) # Function to create a file with Rob's Nanopolish & my Nanop...
#!/usr/bin/env python3 """ Created on Wed Dec 4 18:00:00 2021. @author: yoh """ from dataclasses import dataclass from os import listdir from os import path as os_path from os import rmdir from shutil import rmtree from typing import Tuple, Type, Union from pandas import DataFrame as pDataFrame from so...
#!/usr/bin/env python3 # Parses linux/input.h scanning for #define KEY_FOO 134 # Prints Rust source header files that can be used for # mapping and lookup tables. # # The original version of this file is in libevdev # import re import sys class Bits(object): pass prefixes = [ "EV_", "REL_", "ABS_",...
import ctypes import platform import os import numpy as np import numpy.ctypeslib as ctl # Load the shared library if platform.system() == 'Windows': __GORPHO_LIB__ = ctl.load_library('pygorpho.dll', os.getenv('PYGORPHO_PATH','./')) else: __GORPHO_LIB__ = ctl.load_library('libpygorpho.so', os.getenv('PYGORPHO_PATH',...
#!/usr/bin/env python # encoding: utf-8 import heapq from doxx.datatypes.package import OfficialPackage from doxx.utilities.fuzzysearch import FuzzySearcher from doxx.datatypes.cache import DoxxCache from Naked.toolshed.system import stdout, stderr from Naked.toolshed.network import HTTP def run_search(search_strin...
#!/usr/bin/env python # DRAGONS # # caldb.py # ------------------------------------------------------------------------------ # caldb.py -- local calibration database management t...
# Copyright 2020 Google 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 # # https:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
''' Created on Sep 8, 2015 This file contains methods which wrap the mcml simulation so it can be conveniently called from python. One example for a mcml simulation would be gpumcml: https://code.google.com/p/gpumcml/ @author: wirkert ''' import os import contextlib import logging import subprocess32...
#!/usr/bin/env python3 """ usage: pmga-build [-h] [--outdir STR] [--force] [--silent] [--debug] [--version] pmga-build - Script for creating local BlastDBs from PubMLST alleles optional arguments: -h, --help show this help message and exit --outdir STR Directory to save BLAST databases to --force Over...
import os from nltk import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import metrics from sklearn.model_selection import train_test_split, cross_val_predict import simplejson as json import re import codecs from Classifiers import MutableKNeighborsClassifier, Mutabl...
#!/usr/bin/env python from collections import OrderedDict import wx #--------------------------------------------------------------------------- class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.CLIP_CHILDREN) ...
#!/usr/bin/env python3 # coding: utf-8 # Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust # # 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:/...
# Copyright 2018 Google 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 by applicable law or agreed to in writing, ...
from django import forms from .models import ( Character, CharacterAbilities, CharacterBackground, CharacterSkill, CharacterToolProficiency, Feature, Language, Subclass, Tool ) from .widgets import AbilityListBoxSelect class CharacterForm(forms.ModelForm): class Meta: model = Character fi...
from typing import Any, Union import voluptuous as vol from awesomeversion import AwesomeVersion from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, STATE_ON, __version__ as HAVERSION from homeassistant.core import Context, CoreState, HomeAssistant, callbac...
""" Pytest behavior customizations. """ import os import sys import time import re import itertools import logging import pytest from _pytest.terminal import TerminalReporter from config import load_config, default from reporting import ReportSingleton, TestFunction, TestReport class AgentTerminalReporter(Terminal...
"""IGCSE Past Papers Downloader""" import os import requests import bs4 from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter from . import config def mkdir(name): """Makes a dir if that dir does not exist""" try: os.mkdir(name) except FileExistsError: pass def get_paper_data(pap...
import psycopg2 from random import randint, uniform def queryDB(lists): con = None try: conn_string = "host='ec2-54-83-50-145.compute-1.amazonaws.com' dbname='dad8agdskdaqda' port='5432' user='bxzszdjesssvjx' password='<PASSWORD>'" print ("Connecting to database\n ->%s" % (conn_string)) conn = psycopg2.connect...
# f = open('python_log_file','w') # f.write('Starting python module from OpenFOAM') # f.close() import traceback import sys import matplotlib.pyplot as plt import numpy as np import tensorflow as tf class online_svd_calculator(object): """ docstring for online_svd_calculator: K : Number of modes to trunca...
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand - XBMC Plugin # Conector para streaminto # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # ------------------------------------------------------------ import re from core import httptools from core import...
# Copyright 2021 MosaicML. All Rights Reserved. from __future__ import annotations import logging from dataclasses import asdict, dataclass from typing import Union import torch import yahp as hp from PIL.Image import Image from torchvision.transforms import functional as TF from composer.algorithms import Algorith...
from django.shortcuts import render # from main.models import Person # Create your views here. from django.contrib.auth import update_session_auth_hash from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.shortcuts import render, redirect from django.contrib....
import base64 import json import logging import os import threading import uuid import time import structlog from datetime import datetime from flask import request, render_template, flash from app import app, socketio from app.jwt.encryption import decrypt_survey from app import message_manager from app.messaging.pub...
"""Data fetching """ # MIT License # # Copyright (c) 2019 <NAME> # # 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, cop...
#!/usr/bin/env python3 import argparse import os from pathlib import Path import re import pandas as pd import wmfdata as wmf from wmfdata.utils import print_err import findspark findspark.init("/usr/lib/spark2") this_directory = str(Path(__file__).parent.resolve()) # To do: This way of specifying the Hive database...
from __future__ import print_function import os import sys import json import csv if __name__=='__main__': SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(SRC_ROOT) from datetime import datetime from jinja2 import Template from jinja2 import Environment, PackageLoader ...
""" Parsing of the output from fileinfo. """ import json import re from regression_tests.parsers.text_parser import Text def parse(output): """Parses the given output from fileinfo (`str`). :returns: Parsed representation of the given output (:class:`FileinfoOutput`). """ return F...
# -*- coding: utf-8 -*- ''' Tiene ciertas funciones utiles que son usadas a lo largo del codigo ''' import string import random import httplib2 import base64 from email.MIMEText import MIMEText from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets from oauth2client.file import...
#!/usr/bin/python3 -i # # Copyright (c) 2020 The Khronos Group Inc. # # SPDX-License-Identifier: Apache-2.0 # Description: # ----------- # This script generates a .hpp file that can be included in an application # to generate json data that can then be used to generate the pipeline cache. import os import re import x...
''' -------> Descrição do Exercício <------- Exercício utilizando Listas Faça um algoritmo que, através da digitação pelo teclado, armazene várias cidades e seus estados. Exemplo da estrutura das listas: lista_de_cidades lista_de_estados 0 <NAME> RIO GRANDE DO SUL 1 CANOAS RIO GRANDE DO SUL 2 GRAVATAI RIO GRANDE D...
import dash import dash_html_components as html from dash.dependencies import Input, Output, State from openomics import MultiOmics from openomics_web.layouts import app_layout from openomics_web.layouts.clinical_view import ClinicalDataColumnSelect, ClinicalDataTable from openomics_web.layouts.datatable_view import E...
"""This module wraps the calls to the GPIO interface.""" from pydgilib.dgilib_config import INTERFACE_GPIO from pydgilib_extra.dgilib_extra_config import NUM_PINS from pydgilib_extra.dgilib_interface import DGILibInterface from pydgilib_extra.dgilib_calculations import GPIOAugmentEdges from pydgilib_extra.dgilib_data ...
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
""" SOM-DST Copyright (c) 2020-present NAVER Corp. MIT license """ import torch import torch.nn as nn from pytorch_transformers.modeling_bert import BertPreTrainedModel, BertModel class SomDST(BertPreTrainedModel): def __init__(self, config, n_op, n_domain, update_id, exclude_domain=False): super(SomDST,...
# Copyright 2021 Contributors to the Parsec project. # SPDX-License-Identifier: Apache-2.0 import os from os import listdir from os.path import isfile, join from yaml import safe_load, dump from struct import pack import base64 # Generator functions # Add your new generator function here # TODO: with some import syn...
#!/usr/bin/env python from __future__ import print_function import numpy as np import matplotlib.pyplot as plt def run_old_oqe(fname, key1, key2, freqrange): """ Run old OQE algorithm using capo. """ # Legacy functions to load data and estimate power spectrum import capo legacy_read_files = cap...
import json from django import forms from category.models import Category from django.conf import settings from django.template.loader import render_to_string from django.utils.encoding import smart_text from django.utils.safestring import mark_safe from django.utils.six import unichr from mptt.forms import TreeNodeC...
import torch.nn as nn import torch.nn.functional as F class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) ...
import warnings import numpy as np from yt.testing import \ assert_array_equal, \ assert_array_almost_equal, \ fake_random_ds import yt.utilities.linear_interpolators as lin from yt.utilities.lib.interpolators import \ ghost_zone_interpolate def setup(): pass def test_linear_interpolator_1d(): ...
import re import sys import os import time import logging from datetime import datetime from resources.log_color import ColoredFormatter from resources.parser import Parser from resources.handlers.router import routeSubmission from resources.save import Save from resources.db_interface import DBInterface f...
# MIT License # Copyright (c) 2022 <NAME>™ # 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, merge, publis...
#!/usr/bin/env python3 """ Clone builds a cloning dataset and runs a training run over it. We combine these two steps as the datasets tend to be pretty small so it's simpler to just have all the code together. """ import argparse from pathlib import Path import multiprocessing import time import numpy as np import torc...
# Copyright 2004-present Facebook. All rights reserved. import glob import json import logging import os import subprocess import sys from collections import namedtuple from typing import Dict, List # noqa from . import log LOG = logging.getLogger(__name__) CACHE_PATH = ".pyre/buckcache.json" BuckOut = namedtupl...
from __future__ import division import numpy as np from collections import namedtuple Split = namedtuple('Split', ['feature_ix', 'th', 'X_false', 'y_false', 'X_true', 'y_true']) class TreeNode: """DecisionTree Node. If split node, stores the feature index and the value to make ...
""" usage: partition_dataset.py [-h] [-i IMAGEDIR] [-o OUTPUTDIR] [-r RATIO] [-x] Partition dataset of images into training and testing sets optional arguments: -h, --help show this help message and exit -i IMAGEDIR, --imageDir IMAGEDIR Path to the folder where the image dataset...
from modelrAPI import modelrAPI, Rock from modelr.reflectivity import reflectivity_array from PIL import Image import numpy as np from numpy.random import randn import requests from scipy.interpolate import interp1d import h5py from StringIO import StringIO import md5 import json from bruges.transform import depth_to_...
from .backend import keras from .backend import backend as K class GraphLayer(keras.layers.Layer): def __init__(self, step_num=1, activation=None, **kwargs): """Initialize the layer. :param step_num: Two nodes are considered as connected if they...
# -*- coding: utf-8 -*- """ pysteps.utils.interpolate ========================= Interpolation routines for pysteps. .. autosummary:: :toctree: ../generated/ idwinterp2d rbfinterp2d """ import warnings import numpy as np from scipy.interpolate import Rbf from scipy.spatial import cKDTr...
""" This sub module's purpose is to obtain a new normalized \ dataset for SVR """ import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.decomposition import PCA from sklearn.feature_selection import RFE from sklearn.model_selection import train_test_split from sklearn.preprocessing imp...
# Copyright 2021 MosaicML. All Rights Reserved. """Common settings across both the training and eval datasets. These settings are dataset independent. """ from __future__ import annotations import logging import textwrap from dataclasses import dataclass from typing import Any, Callable, Iterator, Optional import ...
from insights.parsers import logrotate_conf from insights.parsers.logrotate_conf import LogrotateConf from insights.tests import context_wrap import doctest LOGROTATE_CONF_1 = """ # see "man logrotate" for details # rotate log files weekly weekly # keep 4 weeks worth of backlogs rotate 4 # create new (empty) log fil...
#coding:utf-8 from pyglet.gl import * import numpy as np import OpenGL.GL.shaders import ctypes import pyrr import time from math import sin from pyrr import Vector3, matrix44, Matrix44 import time import numpy class ObjLoader: def __init__(self): self.vert_coords = [] self.text_coords = [] ...
import copy class Route: def __init__(self, starting_st, vehicle, hour, time_hor=25): self.starting_station = starting_st self.stations = [starting_st] self.length = 0 self.station_visits = [0] self.upper_extremes = None self.time_horizon = time_hor self.ve...
# check that the given Mozart file covers the time range and the domain plus a 10 degree buffer import argparse import datetime as dt import os import re import sys from netCDF4 import Dataset as ncdat wrf_dt_fmt = '%Y-%m-%d_%H:%M:%S' def shell_error(msg, exitcode=1): print('{0}:\n\t{1}'.format(__file__, msg), f...