text
stringlengths
3.07k
12.6k
# # Copyright(c) 2019 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # import json import re from datetime import timedelta from typing import List from packaging import version from api.cas import casadm from api.cas.cache_config import * from api.cas.casadm_params import * from test_utils.size imp...
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 # model file: example-models/ARM/Ch.17/17.7_latent_glm.stan import torch import pyro import pyro.distributions as dist def init_vector(name, dims=None): return pyro.sample(name, dist.Normal(torch.zeros(dims), 0.2 * torch.ones(dim...
#!/usr/bin/env python3 """ License statement applies to this file (glgen.py) only. """ """ 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 limit...
from __future__ import print_function, division from builtins import range # Note: you may need to update your version of future # sudo pip install -U future import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from sklearn.utils import shuffle from sklearn.model_selection imp...
# # Universidade Estadual do Norte Fluminense - UENF # Laboratório de Engenharia de Petróleo - LENEP # Grupo de Inferência em Reservatório - GIR # <NAME> # May 11th, 2017 """ Messaging pattern module ======================== "In the publish–subscribe model, subscribers typically receive only a subset of the total me...
import pandas as pd import scipy as sp import numpy as np import skbio import itertools import regex def seq2mat(seq,seq_dict): mat = sp.zeros((len(seq_dict),len(seq)),dtype=int) for i,bp in enumerate(seq): mat[seq_dict[bp],i] = 1 return mat def choose_dict(dicttype,modeltype='MAT'): '''Crea...
############################################################################################### # # python package evec consists of all the pythnon functions to call Hedera Java SDKs. # Current version only support to run the server and IoT devices in the same local network # Auther: <NAME> # Version: v.0.0.1 # Projec...
import json import pickle import joblib import pandas as pd from flask import Flask, jsonify, request from peewee import ( SqliteDatabase, PostgresqlDatabase, Model, IntegerField, FloatField, TextField, IntegrityError ) from playhouse.shortcuts import model_to_dict ######################################## # B...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Copyright (c) Ostap developpers. # ============================================================================= ## @file ostap/math/tests/test_math_interpolation.py # Test module for the fi...
import re import json from genie.metaparser import MetaParser class ShowPlatformHardwareSchema(MetaParser): """show platform hardware fed switch active qos queue stats interface FortyGigabitEthernet 1/1/2""" schema = { 'global_hard_limit': int, 'global_soft_limit': int, 'global_hard_b...
import argparse import math import torch import numpy as np from constants import BYR_DROP from featnames import OUTCOME_FEATS, DAYS_SINCE_LSTG, BYR_HIST, \ TIME_FEATS, CLOCK_FEATS, THREAD_COUNT, TURN_FEATS, SLR, META, LEAF, LSTG from env.Composer import Composer from env.const import OFFER_MAPS, THREAD_COUNT_IND, ...
# -*- coding: utf-8 -*- """ First step in preprocessing stage. Thresholding an image removes the color information. Inputs: Original image Outputs: Thresholded image. Resources: http://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html """ import cv2 import numpy as np import math def thr...
from floodberry.floodberry_ed25519 import GE25519 as GE from random import randint from bitarray import bitarray import pickle """ Some basic data structures for use in TDF encryption """ class TDFError(Exception): pass class TDFMatrix: def __init__(self, m: int, lmbd: int = 254): self._M = [[None,Non...
#!/usr/bin/python import pickle import numpy as np import networkx import json import itertools from networkx.drawing.nx_pydot import write_dot from networkx.algorithms.shortest_paths.generic import shortest_path string_symbol_cache = {} def convert_tree(rulename,estimator,feature_names,malware_threshold=0.5): ""...
from random import random, uniform, choice import timeit from structural_calculation import Database, StructuralUnit from xml.etree.ElementTree import ElementTree, Element, XMLParser import xml.etree.ElementTree as ET from xml.dom.minidom import parseString import threading def define_unit(M_y=337.5, M_z=337.5, N=-10...
from sympy.core import C, Expr, Mul, S, sympify from sympy.functions.elementary.piecewise import piecewise_fold from sympy.polys import quo, roots from sympy.simplify import powsimp class Product(Expr): """Represents unevaluated product. """ __slots__ = ['is_commutative'] def __new__(cls, function, ...
#!/usr/bin/env python """ROS Node to expose topics for batteries on the Pi-puck.""" # ROS imports import rospy from sensor_msgs.msg import BatteryState # Constants NAN = float("nan") BATTERIES = { "primary": { "path": "/sys/bus/i2c/drivers/ads1015/11-0048/iio:device0/in_voltage0_raw", "design_capa...
import argparse import fnet.data import importlib import json import numpy as np import os import pandas as pd import tifffile import time import torch import warnings import pdb def set_warnings(): warnings.filterwarnings('ignore', message='.*zoom().*') warnings.filterwarnings('ignore', message='.*end of stre...
# -*- coding: utf-8 -*- # # Copyright 2015 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
import sys import ijson, csv, json, datetime from scipy.stats import lognorm import numpy as np import matplotlib.pyplot as plt sys.path.append('../lib') from accounts.company import Company def main(): enterprises = get_enterprises(2014) distribution_parameters = get_sic_params() actual_size_dists = get_la_...
import datetime import logging from typing import List, Tuple import pyspark.sql as spark from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import VectorAssembler from pyspark.mllib.evaluation import RegressionMetrics from pyspark.sql.functions import ex...
# Copyright (c) 2014 Adafruit Industries # Author: <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...
from subprocess import call import sys import argparse from subprocess import Popen import os, json, time """NOTE: This script includes nearly all tf flag parameters as input arguments, which feed as input through a generated config file.""" parser = argparse.ArgumentParser(description='Run script parameters') # S...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import cv2 import numpy as np import rospy from std_msgs.msg import Bool from sensor_msgs.msg import Image from cv_bridge import CvBridge def detect(frame): font = cv2.FONT_HERSHEY_SIMPLEX img = frame cimg = img hsv = cv2.cvtColor(img, cv2.COLO...
import tensorflow as tf from utils import print_variables, print_layers from tensorflow.contrib.layers.python.layers.layers import batch_norm def _conv3d(input_data, k_d, k_h, k_w, c_o, s_d, s_h, s_w, name, relu=True, padding="SAME"): c_i = input_data.get_shape()[-1].value convolve = lambda i, k: tf.nn.conv3d...
from __future__ import print_function, division import os import sys sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True __author__ = "bigfatnoob" from utils.lib import O from utils.stats import Statistics import time from technix.tech_utils import Point, seed from utils import plotter from technix...
import argparse import time import cv2.cv2 as cv import numpy as np from scipy.signal import find_peaks h_bins = 8 s_bins = 4 v_bins = 4 num_of_bins = h_bins + s_bins + v_bins def check_time(args, cap): frame_count = int(cap.get(cv.CAP_PROP_FRAME_COUNT)) start_frame = int(args.start_sec * cap.get(cv.CAP_PR...
# coding: utf-8 # author: T.XIA """Defines the 'audio' model used to classify the VGGish features.""" from __future__ import print_function import sys import model_params as params import tensorflow as tf import tf_slim as slim sys.path.append("../vggish") import vggish_slim # noqa: E402 def define_audio_slim( ...
import collections import os from pathlib import Path import pickle import random import urllib from io import open import numpy as np def maybe_download(filename, expected_bytes): """ download text8.zip :param filename: :param expected_bytes: :return: """ url = 'http://mattmahoney.net/dc/'...
"""Command Line Interpreter to interact with LC7001 HOSTs Run with --help to see command line usage. This code serves as a demonstration of expected lc7001.aio usage: There will be some type(s) of Hub(s) to add behavior beyond that of a Connector (which is a message Authenticator, Emitter, Receiver and Sender). Here...
""" script for training the MSG-GAN on given dataset """ import argparse import numpy as np import torch as th import yaml from torch.backends import cudnn # define the device for the training script device = th.device("cuda" if th.cuda.is_available() else "cpu") # enable fast training cudnn.benchmark = True # set...
import logging import os from copy import deepcopy from typing import Tuple, Dict, Optional, List, Any import dpath from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.models.consts import YAML_COMMENT_MARK from checkov.common.parallelizer.parallel_runner import parallel_runn...
import os import sys import cv2 import yaml import logging import argparse import os.path as osp import numpy as np sys.path[0] = os.getcwd() from utils.log import logger from utils.meter import Timer import data.video as videodataset from utils import visualize as vis from utils.io import write_mot_re...
from enum import Enum import numpy as np import cv2 class CameraFacing(Enum): FRONT = 0 REAR = 1 class FrameHalf(Enum): LEFT = 0 RIGHT = 1 def center_crop(image, width, height, nudge_down=0, nudge_right=0): x = image.shape[1]/2 - width/2 y = image.shape[0]/2 - height/2 return image[int(y+...
from flask import current_app as app from bson.objectid import ObjectId import ext.auth.acl as acl_helper from ext.app.eve_helper import eve_abort import sys from pprint import pprint class Anon(object): def __init__(self): self.persons = [] def assign(self, person): """Keep track of all assi...
from doubleLinkedList import _DoublyLinkedBase from doubleLinkedList import Empty class PositionalList(_DoublyLinkedBase): """A sequential container of elements allowing positional access""" class Position: """An abstraction representing the location of a single element.""" def __init__(self...
#!/usr/bin/env python # coding: utf-8 """ RabbitMQ client module """ from .base import IConnect, IProduce, IConsume from .base import MQAuthorizeException, MQConnectException from .consts import RabbitConfKeys import pika import logging from time import sleep log = logging.getLogger(__name__) class RabbitMQConnect...
import socket import subprocess import os import sys if sys.version_info.major >= 3: # For mypy PEP-484 static typing validation from typing import Set # NOQA from typing import List # NOQA from typing import Tuple # NOQA from typing import Iterable # NOQA from typing import Op...
import typing from pathlib import Path from collections import OrderedDict import re from pprint import pprint from warnings import warn from ..core.Tearer import TearingSpec, RipAction, SymlinkAction from ..distros.debian import Debian from ..distros.debian.utils import controlDictToArgs, debianPackageRelationKwargs ...
from copy import copy from typing import Tuple, Union, Optional import numpy as np import torch from PIL import Image from torch.utils.data import Dataset as TorchDataset from torchvision import transforms from continuum.viz import plot_samples class TaskSet(TorchDataset): """A task dataset returned by the CLLo...
#importation from math import * import kandinsky as kdk import ion as ion from time import * #on définit les couleurs ici BLANC = kdk.color(255,255,255) NOIR = kdk.color(0,0,0) GRIS = kdk.color(220,220,220) #on dessine le cadre du tableau et les numéros de coordonnées def colonnes(): #les colonnes x_colonnes =...
#!/usr/bin/env python import sys import os.path import pycast from PySide2 import QtCore, QtGui, QtWidgets from PySide2.QtCore import Qt, Slot, Signal # custom event for handling change in freeze state class FreezeEvent(QtCore.QEvent): def __init__(self, frozen): super().__init__(QtCore.QEvent.User) self.fr...
import argparse import cv2 import numpy as np from helper import handle_pose, preprocessing from inference import Network from t_shirt_coords import TShirt, COMPENSATE_HEIGHT_TSHIRT TShirt = TShirt() # Global dictionary for Human coordinates HUMAN_COORDS = { 'NECK': 0, 'LEFT_SHOULDER': 0, 'RIGHT_SHOULDER...
#!/usr/bin/python # (c) 2016, <NAME> <<EMAIL>> # # This 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) any later version. # # This module is dist...
import json from multiprocessing import Process, Queue, Lock, Event import multiprocessing import threading from queue import Empty import selectors import datetime import time from logging.handlers import QueueHandler from pathlib import Path import debug_logger import io_connections def read_json(filepath): pri...
""" Multi-device Jacobi iteration using entirely Parla kernels. This example shows how to write CUDA style kernels within Parla to optimize GPU kernels. """ import os import time import numpy as np import numba.cuda import cupy from parla import Parla from parla.array import copy from parla.cuda import gpu from par...
import pytest import webtest from ichnaea.cache import configure_redis from ichnaea.db import configure_db from ichnaea.geoip import GeoIPNull from ichnaea.webapp.config import main def _make_app( _db=None, _http_session=None, _geoip_db=None, _raven_client=None, _redis_client=None, _position_...
import argparse import os import random import sys import numpy as np import torch from torch.autograd import Variable from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from config import cfg from model.models import ResNet18 os.environ["CUDA_VISIBLE_DEVICES"] = "1" test_...
#!/usr/bin/env python3 import argparse import json import os import sys from clint.textui import puts, colored, indent from google.cloud import bigquery from jinja2 import Template, FileSystemLoader, Environment from os import path from pygments import highlight from pygments.lexers.sql import SqlLexer from pygments.f...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved import torch import torch.nn as nn from transformers import GPT2Tokenizer from .model.attention import AttentionLayer from .model.embedding import PositionalEmbedding, TokenEmbedding from .model.feedforward import Posi...
import os import csv import torch import numpy as np import pandas as pd import seaborn as sns from plot import * from os.path import join from pathlib import Path from sklearn.cluster import KMeans from collections import Counter from torch.utils.data import DataLoader, Subset from customLoader import * from torchvi...
import math from typing import List, Dict, Any, Optional from django.templatetags.static import static from django.db import models from . import utils from .models import Medium, MediumResized class MediumForViewManager(models.Manager): def get_queryset(self): return super().get_queryset().prefetch_rel...
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime from dask import dataframe as dd import numpy as np import pandas as pd from covsirphy.util.error import deprecate, SubsetNotFoundError from covsirphy.cleaning.cbase import CleaningBase class PopulationData(CleaningBase): """ Data cl...
import glob import os import threading import time from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta from multiprocessing import Lock, Manager from hayabusa import HayabusaBase from hayabusa.errors import unexpected_error, RESTResultWaitTimeout from hayabusa.rest_client import ...
""" $Revision: 1.2 $ $Date: 2010/05/18 07:56:00 $ Author: <NAME> (<EMAIL>) Affiliation: Space Telescope - European Coordinating Facility WWW: http://www.stecf.org/software/slitless_software/axesim/ """ from __future__ import absolute_import, print_function import os import os.path import sys import string from astropy...
import serial # need to "pip install pyserial" for this to work import sliplib # need to "pip install sliplib" for this to work import struct from time import sleep # Pad a string or bytes object out to a multiple of 4 octets def OSCpad(s): if isinstance(s,str): # needs a \0 terminator r = bytes(s.encode(...
#!/usr/bin/env python3 """ This program creates simulated votes taht have tallies similar to the real tallies from the Alameda County, CA 2016 presidential election. MIT License Copyright (c) 2016 <NAME>, <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ...
''' convert.py <NAME>, 10/14/2021 ''' import csv def main(): with open('athlete_events.csv', mode ='r')as file: csv_file = csv.reader(file) athlete_information_file = open('athlete_information.csv', 'w') athlete_names_file = open('athlete_names.csv', 'w') gam...
import tkinter as tk from tkinter import * from tkinter import filedialog, messagebox, Button, Label, Canvas from PIL import ImageTk, Image, ImageGrab import cv2 from tensorflow import keras import numpy as np import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' class Model: def __init__(self): pass ...
#!/usr/local/bin/python3 import re import os import io import sys import common import pywikibot ISBN_13 = 'P212' ISBN_10 = 'P957' OCLC_ID = 'P243' PAGE_NUM_ID = 'P1104' BOOK_TEMPLATE = 'Infobox book' ISBN_PROPS = { 10: ISBN_10, 13: ISBN_13 } ALL_PROPS = (PAGE_NUM_ID, OCLC_ID, ISBN_13, ISBN_10) # For basic validation...
from django.contrib.auth.decorators import login_required from django.core import serializers from django.http import JsonResponse from django.shortcuts import render, get_object_or_404 from django.utils import timezone from ..models import Tag, TagRelationship, CaseStudy, MedicalHistory, Medication, Attempt, Comment,...
#!/usr/bin/python3 from time import time import sys import dbus from ble.advertisement import Advertisement from ble.service import Application, Service, Characteristic, Descriptor from sensors.brightness_sensor import BrightnessSensor from sensors.volume_sensor import VolumeSensor GATT_CHRC_IFACE = 'org.bluez.Ga...
import face_recognition from scipy import misc import numpy as np from skimage import transform import os.path import urllib.request import time import requests START_MONTH = 11 START_DATE = 17 START_SLOT = 6 imageCounter = 12500 DESIRED_X = 32 DESIRED_Y = 21 DESIRED_SIZE = 24 FINAL_IMAGE_WIDTH = 64 FINAL_IMAGE_HEI...
""" Target Problem: --------------- * Predict the evolution of brain connectivity over time. Proposed Solution (Machine Learning Pipeline): ---------------------------------------------- * Outlier Elimination with Isolation Forest -> Standard Scaler -> PCA -> RandomForest Input to Proposed Solution: -----------------...
# external # built-in from pathlib import Path import attr import pytest # project from dephell import converters from dephell.controllers import DependencyMaker, Graph, RepositoriesRegistry from dephell.models import Requirement, RootDependency root_path = Path(__file__).parent.parent / 'requirements' @pytest.ma...
from flask import Flask from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from datetime import datetime, date, timedelta import pytz db = SQLAlchemy() shopping = db.Table('shopping', db.Column('product_id', db.Integer, db.ForeignKey('product.id')), db.Column('c...
# 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 applicable law or agreed to in...
import json from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.db import IntegrityError from django.db.models import Q from django.http import Http404, HttpResponse, HttpResponseForbidden from django.shortcuts import ge...
import numpy as np from check import topsis import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor import numpy as np import pandas as pd from mcdm import executors as exe #impact impact = [0,1,1,1,1,1...
from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.http import HttpResponseRedirect, JsonResponse # HttpResponse from django.shortcuts import render, get_object_or_404 from django.urls import reve...
import numpy as np import pandas as pd from math import ceil import cv2 import zipfile from tqdm import tqdm from keras.applications.vgg16 import VGG16, preprocess_input from multiprocessing import Value, Pool import gzip from pathlib import PurePath from scipy import sparse from threading import Thread from queue impo...
import math import turtle from abc import ABC, abstractmethod class Shape(ABC): def __init__(self, center=(0, 0), width=100, height=100, rotation=0): self.center = center self.width = width self.height = height self.rotation = rotation self.turtle = turtle.Turtle() ...
import datetime import sys import traceback import uuid from collections import namedtuple from argh import arg, ArghParser, expects_obj from csvuploader import HeaderCsv from csvuploader.version import VERSION_STRING import py.path import appdirs import yaml import time import logbook from logbook import StreamHandl...
""" .. module: dispatch.plugins.dispatch_jira.plugin :platform: Unix :copyright: (c) 2019 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. """ from jinja2 import Template from jira import JIRA from typing import Any, List from dispatch.decorators import apply, counter, ...
# -*- coding: utf-8 -*- #!/usr/bin/env python3 """ This module contains all the common functions regularly used on the extraction task. Author: <NAME> """ import urllib.request import urllib.error import urllib.parse import sys import csv import spacy from bs4 import BeautifulSoup from nameparser import HumanName ...
import requests from bs4 import BeautifulSoup from time import sleep import datetime import random class CraigslistCity: def __init__(self, Name, URL): self.name = Name self.url = URL class CraigslistListing: def __init__(self, TimePosted, ID, Title, Link): self.TimePosted = TimePosted self.Title = Title ...
from keras.models import Model from keras.optimizers import Adam, SGD from keras.layers.core import Reshape from keras.layers import Input, Conv2DTranspose,Dropout, BatchNormalization, Conv2D, MaxPooling2D,\ concatenate, Activation,add,UpSampling2D # batchnormalization 后激活 def BatchActivate(x): x = BatchNormal...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 15 12:06:03 2017 @author: <NAME> """ from aerodynamics import Compression, Expansion import math, csv import numpy as np from argparse import ArgumentParser from matplotlib.transforms import Affine2D import matplotlib.pyplot as plt from matplotlib.p...
#! /usr/bin/python3 # # pylint: disable=line-too-long, missing-docstring, logging-format-interpolation, invalid-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.apach...
from random import randint import numpy as np import pandas as pd import pytest from cognite.v05 import depthseries, dto DS_NAME = None DS2_NAME = None @pytest.fixture(autouse=True, scope="class") def ts_name(): global DS_NAME global DS2_NAME DS_NAME = "test_ds_{}".format(randint(1, 2 ** 53 - 1)) D...
import json import os import re import sys import singer import time from subprocess import Popen, PIPE, STDOUT from dynamic_singer import helper, function from typing import Callable, Dict from herpetologist import check_type from tornado import gen from prometheus_client import start_http_server, Counter, Summary, Hi...
import tempfile from collections import defaultdict from typing import Any, Dict, List, Optional import hydra import numpy as np import pandas as pd from omegaconf import DictConfig from optuna import logging from pytorch_lightning import ( Callback, LightningDataModule, LightningModule, Trainer, s...
# Copyright: 2005-2011 <NAME> <<EMAIL>> # License: GPL2/BSD __all__ = ("tree", "ConfiguredTree") import errno from functools import partial import os import stat from snakeoil import compatibility, data_source, klass from snakeoil.demandload import demandload from snakeoil.fileutils import readfile from snakeoil.map...
# Projeto 04 - Voto Votado from datetime import date from random import choice from time import sleep ## Função pra limpar terminal def clear(): import platform import os if platform.system() == 'Windowns': os.system('cls') elif platform.system() == 'Linux': os.system('clear') else...
# Copyright 2012 OpenStack Foundation. # 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 req...
# -*- test-case-name: twisted.test.test_paths.ZipFilePathTestCase -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ This module contains implementations of IFilePath for zip files. See the constructor for ZipArchive for use. """ __metaclass__ = type import os import time ...
from collections import defaultdict from queue import PriorityQueue from typing import Dict, Tuple, List, Optional import networkx as nx from days import AOCDay, day DEBUG = True NEIGHBOURS = [(-1, 0), (0, -1), (1, 0), (0, 1)] DIAGONALS = [(-1, -1), (-1, 1), (1, -1), (1, 1)] class Map: field = defaultdict(str)...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (c) 2015 <NAME>, SUTD # # 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...
import abc from simplejson.errors import JSONDecodeError from tempfile import mktemp from cleo import Command from shutil import copyfileobj import requests from typing import Optional, Union from distutils.version import LooseVersion from collections import OrderedDict from cleo.helpers import Argument from pathlib im...
from plugin.core.constants import PLUGIN_IDENTIFIER import gettext import locale import logging import os import platform DEFAULT_LOCALE = 'en_US' log = logging.getLogger(__name__) class PathEnvironment(object): # TODO confirm validity of this on *nix and OS X def __init__(self, core): self._core ...
# coding: utf-8 """ 뉴스 Engine """ # std lib import arrow from django.conf import settings from bs4 import BeautifulSoup import feedparser import datetime import time import logging from nyuseu.models import Feeds, Articles from nyuseu.rss import Rss from rich.console import Console # Get an instance of a logger l...
from flask import Flask, request from flask_cors import CORS from fate_manager.service import site_service from fate_manager.utils import detect_utils from fate_manager.utils.api_utils import server_error_response, get_json_result manager = Flask(__name__) CORS(manager, supports_credentials=True) @manager.errorhand...
'''GoogLeNet with PyTorch.''' import os import torch import torch.nn as nn import torch.onnx as onnx from torch.autograd import Variable class Inception(nn.Module): def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes): super(Inception, self).__init__() # 1x1 conv branch ...
import numpy as np import math from corai_util.tools import function_iterable # defines the coefficients for fractional ADAMS method in order to compute a SDE path. # it needs the number of coefficients as well as the alpha of roughness. def fractional_ADAMS(k, alpha, DELTA): # a needs k+2 elements, because j \in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ feature_ranking.py Explore weighted feature rankings produced by random forests in trees.py Authors: – <NAME>, 2017 (<EMAIL>) @author: jon.clucas """ import os, sys if os.path.abspath('../../') not in sys.path: if os.path.isdir(os.path.join(os.path.abspath('.....
import argparse import tkinter as tk from collections import OrderedDict, defaultdict from pathlib import Path from opensfm import dataset, io from . import GUI from .gcp_manager import GroundControlPointManager from .image_manager import ImageManager def parse_args(): parser = argparse.ArgumentParser(descripti...
# app.py from os import name import threading from flask import Flask, render_template, send_file, Response, abort, jsonify, request, url_for, redirect, logging from sqlalchemy.sql import text # Para o upload de arquivos from werkzeug.utils import secure_filename # Para a autenticação from flask_httpauth import HTTPBas...
#! /usr/bin/env python3 """ The main file for running cyberPhys """ from besspin.base.utils.misc import * import besspin.target.launch from besspin.base.threadControl import ftQueueUtils from besspin.cyberPhys import otaserver, infotainmentserver # Import for CAN bus from besspin.cyberPhys.cyberphyslib.cyberphyslib.c...
import torch import pandas as pd import PIL import os import matplotlib.pyplot as plt import time import numpy as np from torchvision import datasets, models, transforms import torch.nn as nn import torch.optim as optim from torchvision.transforms import ToTensor class CustomDataset(torch.utils.data.Dataset): def ...