text
stringlengths
3.07k
12.6k
"""Profiles""" import os import random import sqlite3 from datetime import datetime import scrapy from scrapy.http import Request from scrapy.selector import Selector from scrapy_jsonschema.item import JsonSchemaItem from ..items import ParliamentPipeline parties_dictionary = { "ПП ГЕРБ": "GERP", "БСП за БЪ...
# stdlib imports import warnings import os.path import sys from collections import OrderedDict # third party imports import netCDF4 as netcdf import rasterio import numpy as np from rasterio.profiles import DefaultGTiffProfile # local imports from mapio.geodict import affine_from_geodict def get_nodata(grid): i...
from dataclasses import dataclass from typing import List, Tuple, Callable import torch from cached_property import cached_property from graph_pit.graph import Graph from graph_pit.loss.base import GraphPITBase, LossModule __all__ = [ 'GraphPITLoss', 'GraphPITLossModule', 'graph_pit_loss', ] def solve_...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import KFold from sklearn.svm import LinearSVC import numpy as n...
#!/usr/bin/env python """ Convert all recipes into feedstocks. This script is to be run in a TravisCI context, with all secret environment variables defined (BINSTAR_TOKEN, GH_TOKEN) Such as: export GH_TOKEN=$(cat ~/.conda-smithy/github.token) """ from __future__ import print_function from conda_smithy.github i...
#!/usr/bin/python # # Copyright (c) 2019 <NAME>, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
#coding=utf-8 from .dt import * from .Match import * import sys version = sys.version < '3' tdt = Datatype() tcs = Constructor() tdt.List('a') == tcs.Nil() \ | tcs.Cons('hd','tl') List = tdt.List Nil = tcs.Nil nil = Nil() Cons = tcs.Cons @matcher(Nil,False) def null(self): return True @ma...
import hashlib import hmac import random from datetime import datetime from functools import wraps from flask import request from googleapiclient.errors import HttpError from server import config from server.log import log from server.services import calendar_service, slack_service _POTENTIAL_REASONS_ = [ "Would...
#Import Tkinter from tkinter import * import tkinter as tk from tkinter import filedialog from PIL import ImageTk,Image import subprocess,io #------------------------ from imageai.Detection import ObjectDetection #Import ImageAi import os #Import Os root = tk.Tk() root.title('ImageAi ile Nesne Algılama') #Pencere Başl...
"""Module for Pokemon Helpers calculations.""" from math import floor from random import uniform from random import random from config import POKEMON_DATA from config import WEAKNESS_CHART from config import (BRN_STATUS, PSN_STATUS, TOX_STATUS) def calculate_stat(base_val, ev_val, level): """ Calculate the ...
""" 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) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Mar 27 15:31:29 2017 @author: robert """ import unittest import warnings import sys #ways to execute this test_file #python -m mono.tests.test_file.py ( __name__ ='__main__' and package ='mono.tests') #python tests/test_file.py ( __name__ ='__main__' ...
#! /usr/bin/python from __future__ import print_function import os import sys import random import string import subprocess from collections import defaultdict from _lib.bootstrapping import from_project_root, from_env_bin from _lib.params import APP_NAME from _lib.frontend import frontend, ember from _lib.db import ...
import numpy as np from random import randint, random def objective_function(vector): s = sum([i**2 for i in vector]) return abs(s) def random_vector(minmax): rand_vector = [minmax[i][0] + ((minmax[i][1]-minmax[i][0]) * random()) for i in range(len(minmax))] return rand_vector def create_particle(search_...
import os import pytest import re import sys import tempfile # We're not using python packages, so we have to solve the path problem the old way. sys.path.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))) import rfcs @pytest.fixture def scratch_space(): x = tempfile.Temporar...
import pexpect from threading import Thread mpg_outs = [ { "mpg_code": "@P 0", "action": "user_stop", "description": "Music has been stopped by the user." }, { "mpg_code": "@P 1", "action": "user_pause", "description": "Music has been paused by the user." ...
#DustSim IRL :) #Allows us to play around and model real dust particles using le Gauss #Also enables some smart mode switching between peak-detect and bgdetect. #@Alto et al. #Imports - verify if they are on Your machine :) import serial import turtle import math import random import time import statistics #Globals s...
import heterocl as hcl import hlib import numpy as np hcl.init() def softmax(out, x): assert len(x.shape) == 2, "only support 2-dim softmax" m, n = x.shape k = hcl.reduce_axis(0, n) max_elem = hcl.compute((m,), lambda i: hcl.max(x[i, k], axis=k)) k = hcl.reduce_axis(0, n) expsum = hcl.compute(...
import copy import tarfile import os import os.path import itertools import math import numpy as np import scipy.signal as signal from pysit.util.image_processing import blur_image from pysit.gallery.gallery_base import GeneratedGalleryModel from pysit import * #PML, Domain __all__ = ['LinearIncreasedMediumModel',...
import logging import subprocess import os import sys import pysam from distutils.version import LooseVersion # Check java version to make sure it is Java 8 MY_DIR = os.path.dirname(os.path.realpath(__file__)) VARSIMJAR = os.path.realpath(os.path.join(MY_DIR, "VarSim.jar")) RTGJAR = os.path.realpath(os.path.join(MY_DIR...
# -*- coding: utf-8 -*- import bs4, pyexcel_xls, random, re, requests, time from tqdm import tqdm from collections import OrderedDict data_save = OrderedDict() actor_name = [] actor_id = [] actor_movie_count = [] headers = { # 请求头 'Host': 'movie.douban.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64...
# Copyright 2011 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
#!/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:/...
#!/usr/bin/env python from typing import List from pypozyx import (Coordinates, DeviceCoordinates, SingleRegister, DeviceList, PozyxConstants, get_first_pozyx_serial_port, PozyxSerial) from flux_sensors.models import models NUMBER_OF_CALIBRATION_CYCLES = 10 class LocalizerError(Exception): "...
# Copyright (c) 2015 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 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # By <NAME> (Naereen) # https://github.com/Naereen/gym-nes-mario-bros # MIT License https://lbesson.mit-license.org/ # from __future__ import division, print_function # Python 2 compatibility from collections import deque import numpy as np import matplotlib.pyplot as plt...
import os import sys import json import collections from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction import numpy as np from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') def load_txt(path): with open(path, encoding='UTF-8', errors='ignore')...
#!/usr/bin/env python3 __description__ = \ """ Take a fasta file with an alignment, grab the secondary structure and solvent accessibility for each site, then create a stockholm file encoding secondary structure call and accessiblity for input to phyml-ss. """ __author__ = "<NAME>" __date__ = "121101" __usage__ = "prep...
import os import datetime import tempfile import logging import json import argparse from functools import partial import numpy as np import ray from ray.rllib.agents.registry import get_agent_class from ray.tune.registry import register_env from ray.rllib.agents import dqn as ray_dqn from ray.tune.logger import pret...
from torch import nn from efficientnet_pytorch import EfficientNet from torchvision import models import pretrainedmodels import torch import torch.nn.functional as F # sorted( # name for name in models.__dict__ # if name.islower() and not name.startswith("__") and callable(models.__dict__[name]) # ) # ['alexn...
''' Coded by Z1 :) More features are underway! Email questions/concerns/feature requests at <EMAIL> or via twitter: @z1rk4 ''' from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream from tweepy import API from tweepy import Cursor import tweepy import time import datet...
# Copyright (c) 2015 Rackspace, 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 wr...
#!/usr/bin/env python3 # # Copyright (c) 2018-2022 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Check for duplicate includes. # Guard against accidental introduction of new Boost dependencies. # C...
import time import torch import numpy as np from hpbandster.core.worker import Worker from hpbandster.optimizers import BOHB as BOHB import hpbandster.core.nameserver as hpns import hpbandster.core.result as hpres from hpo.model import MyMetaLearner, MyLearner, MyPredictor from hpo.helpers import * from hpo.utils im...
import faiss import numpy as np from sklearn import preprocessing from utils import load_image, get_image_paths class Analyst: def __init__(self, V_dict): self.classes = list(V_dict) self.V_dict = V_dict self._V_dict = V_dict # save a copy that won't be @property def V_norm_dic...
# Copyright 2017 Google 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 writing,...
from django.views.generic import DetailView, ListView, UpdateView, CreateView from .models import Category, ProductType, Product, ProductVariant, Attribute, AttributeValue, ProductImage, VariantImage,Stock,StockTransaction from .forms import CategoryForm, ProductTypeForm, ProductForm, ProductVariantForm, AttributeForm,...
''' Take your oracle function from #12. Now generate a random count of random bytes and prepend this string to every plaintext. You are now doing: AES-128-ECB(random-prefix || attacker-controlled || target-bytes, random-key) Same goal: decrypt the target-bytes. ''' import random from AES_ECB import EncryptAESECB,Decr...
from pytorch3d.transforms import rotation_6d_to_matrix, quaternion_to_matrix import torch.nn.functional as F from src.geometry.vector import cross_product, normalize_vector import torch import numpy as np # m: batch*3*3 # out: batch*4*4 def get_4x4_rotation_matrix_from_3x3_rotation_matrix(m): batch_size = m.shape[...
# # 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 # distri...
import torch import random import torchvision import os import my_custom_transforms as mtr from dataloader_rgbdsod import RgbdSodDataset from torch.utils.data import DataLoader ########################################[ Optimizer ]######################################## def get_optimizer(mode, train_params, lr, kwarg...
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:13:58 2019 @author: rocco """ import os import matplotlib.pyplot as plt import numpy as np import pandas as pd files = [i for i in os.listdir("../data/mipas_pd")] files = files[19:24] classifier_type = "labels_svm_pc_rf_2" def plot_bar(files, classifier...
""" Adapter for ODIN control FileInterface. This class implements a simple adapter used for retrieving config file(s) <NAME>, STFC Detector Systems Software Group <NAME>, STFC Detector Systems Software Group """ import logging import tornado import time from concurrent import futures import os from tornado.escape i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import logging import psutil import subprocess import os import yaml from threading import Thread import srvdb import requests as orig_requests import time from flask import Flask from flask import request from two1.commands.config import Config from two1.wa...
# -*- coding: utf-8 -*- # # Copyright (C) 2019-2020 CERN. # Copyright (C) 2019-2020 Northwestern University. # # Invenio App RDM is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Blueprint used for loading templates. The sole purpose...
import os import sys import glob import psycopg2 import pandas as pd from sql_queries import * def process_song_file(cur, filepath): """Extracts songs and artists from the JSON data source and inserts them into the database. Args: cur: The PostgreSQL cursor object. filepath (str): Th...
from rest_framework import serializers from rest_auth.models import TokenModel from django.contrib.auth.models import User from rest_framework_gis.serializers import GeoFeatureModelSerializer from api.fields import Base64ImageField from .models import MetadataObservation, Help, Phenomenon, Parameter, Dictionary, Pheno...
# coding:utf-8 import re import six import codecs import pickle import functools import heapq as hq from pathlib import Path from collections import defaultdict # should be directory contains the files ending with '.txt' data_dir = '10_July/' # save path for compressed file, need to determine further save_path = '10_...
#!/usr/bin/env python """ Based on storcli.py example from node_exporter, with substantial changes. https://github.com/prometheus/node_exporter/blob/master/text_collector_examples/storcli.py megaraid_controllers{controller,model}=1 megaraid_controller_memory_errors{controller,correctable=y|n}=counter megaraid_contro...
#!/usr/bin/env python3 import argparse from operator import add, sub, mul import sys import time import cv2 import numpy as np BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) WHITE = (255, 255, 255) def brighten(rgb, valu...
# HACK: if the profile plugin is imported before the coverage plugin then all # the top-level code in pytest_profiling will be omitted from # coverage, so force it to be reloaded within this test unit under coverage from six.moves import reload_module # @UnresolvedImport import pytest_profiling reload_module(pytest_...
""" Schlagzeilengenerator ~~~~~~~~~~~~~~~~~~~~~ A small web application to generate tabloid press headlines. :copyright: (c) 2012-2016 by <NAME>, <NAME>. :license: BSD 3-clause, see LICENSE for more details. """ import os import sys import random import json from urllib.parse import quote_plus fr...
""" pgsql_holidays Script for building the holidays schema in a configured PostgreSQL database from source SQL files """ # Standard Imports import json import os import re # PyPi Imports import psycopg2 import psycopg2.extras # Local Imports ## None ##################################################################...
############################################################################### # # Copyright (C) 2021 - Skinok # # This program 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,...
# encoding=utf8 import numpy as np import networkx as nx import scipy.sparse import scipy.sparse as sp from scipy import linalg from scipy.special import iv from sklearn import preprocessing from sklearn.utils.extmath import randomized_svd import argparse import time class ProNE(): def __init__(self, graph_file, ...
"""Yandex Authentication Views You may see developer docs at http://api.yandex.com/oauth/ """ import uuid from pyramid.httpexceptions import HTTPFound from pyramid.security import NO_PERMISSION_REQUIRED import requests from ..api import ( AuthenticationComplete, AuthenticationDenied, register_provider, ...
from sklearn.metrics import r2_score as r2 from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error as mse import pandas as pd import numpy as np import constant import joblib import model_pipeline import plotly.express as px original = pd.read_csv(constant.PATH + 'life_expec...
import time import sys from collections import defaultdict from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from pycocotools import mask as COCOmask import json import numpy as np # Percentage movement on (x,y,w,h). # Each movement will generate a json file, consisting of 'dious', 'act', '...
import hashlib import json import os import threading import time from dbx import IsDirError class Config(object): def __init__(self, config_file): self._raw = json.load(open(config_file)) def __getitem__(self, key): return self._raw[key] class ETagCache(object): def __init__(self, dbx_f...
#!/usr/bin/env python # -*- coding: utf-8 -*- ## ## @file train_classification.py ## @brief Trainer Class for Classification CNN Training ## @author Keitetsu ## @date 2020/05/22 ## @copyright Copyright (c) 2020 Keitetsu ## @par License ## This software is released under ...
import bpy class ShaderNodeBuilding: """Base utilities to construct node trees""" node_tree = None inputs = {} outputs = {} def init_tree(self, name): self.node_tree = bpy.data.node_groups.new(name, 'ShaderNodeTree') self.node_tree.nodes.new('NodeGroupInput') self.node_tr...
import unittest from .molecule import Molecule from .inchi import * class InChITest(unittest.TestCase): def test_constructor(self): inchi1 = InChI('InChI=1S/foo') self.assertTrue( inchi1 is not None) with self.assertRaises(InchiException): inchi1 = InChI('foo') def test...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import collections import sys import numpy as np import errno import logging import json import _jsonnet import torch from pytorch_memlab import MemReporter from cluster import Span def initialize_f...
import operator from functools import reduce from django.contrib.auth.models import User from django.db.models import Q from django.utils import timezone from rest_framework import generics, permissions, filters, mixins, status from rest_framework.generics import get_object_or_404 from rest_framework.permissions impor...
import pdb import torch import torch.nn as nn import numpy as np import torch.nn.functional as F class MLPBlock(nn.Module): def __init__(self, out_channel, dimension, with_bn=True): super(MLPBlock, self).__init__() self.layer_list = [] if dimension == 1: for idx, channels in en...
# -*- 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 ...
# MIT License # # Copyright (C) IBM Corporation 2019 # # 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...
# -*- coding: utf-8 -*- __author__ = '<NAME> and <NAME>' __copyright__ = 'Copyright 2020, The arXivDigest project' from datetime import datetime from flask import Flask from flask import g from flask import jsonify from flask import make_response from flask import request import arxivdigest.api.database as db impor...
from collections import OrderedDict import pandas as pd def perf_attrib(returns, positions, factor_returns, factor_loadings): """ Attributes the performance of a returns stream to a set of risk factors. Performance attribution determines how much each risk factor, e.g., momentum, the technology secto...
"""This module is not considered part of the public interface. As of 2.3, anything here may change or be removed without warning.""" import platform import os import requests import six import trafaret as t from requests_toolbelt.multipart.encoder import MultipartEncoder from six.moves.urllib_parse import urlparse f...
# [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # 1. Redistributions of source code must retain the above # copyright no...
#!/usr/bin/env python import argparse import os import subprocess import sys import textwrap from pathlib import Path # compat mappings ENV_TO_ENV: dict[str, str] = { "INPUT_CONFIG": "SEMGREP_RULES", "BASELINE_REF": "SEMGREP_BASELINE_COMMIT", "SEMGREP_BASELINE_REF": "SEMGREP_BASELINE_COMMIT", "INPUT_PU...
""" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Real time animation of hyperbolic tilings with pyglet and glsl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Code adapted from <NAME>'s excellent shadertoy program at "https://www.shadertoy.com/view/3tsSzM" Again Matt's program h...
# coding: utf-8 from argparse import ArgumentTypeError import mock import pytest from cmdtree import types class TestParamTypeFactory: def setup_method(self, method): self.instance = types.ParamTypeFactory() def test_should_call_return_argparse_kwargs(self): assert self.instance() == {"typ...
# SPDX-FileCopyrightText: 2020 <NAME> <<EMAIL>> # # SPDX-License-Identifier: Apache-2.0 from enum import Enum from typing import List, Tuple, Optional from codeprep.preprocess.core import ReprConfig from codeprep.preprocess.metadata import PreprocessingMetadata, with_empty_metadata, unwrap_single_string from codeprep...
# grid_generation_utils import numpy as np def height_filter(pc_input, height_max): # To filter out possible noise in the raw LiDAR pc input mask = np.ones(pc_input.shape[0], dtype = bool) mask = np.logical_and(mask, pc_input[:, 2] < height_max) pc_filtered = pc_input[mask, :] return pc_filtered def get_stati...
import random import time import mesh as meshtools from random import randint from typing import List, Tuple from PIL import Image, ImageDraw, ImageChops, ImageStat # Type definitions tyPosition = Tuple[float, float] tyColor = Tuple[int, int, int, int] tyColors = List[tyColor] tyVertex = dict tyVertices = List[List[...
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # ver. < 3.0 import ipdb from datetime import datetime import asyncio import datetime from .model import main, TableRegistry # https://stackoverflow.com/questions/8884188/how-to-read-and-write-ini-file-wit...
from flask import render_template, url_for, flash, redirect, request, session from surprise.forms import RegistrationForm, AddRecepientForm from surprise.models import Creator, Recepient from surprise import app, db from datetime import datetime import hashlib import time # change the format of the recepient list # ge...
import torch.nn as nn import torch.utils.model_zoo as model_zoo from .resnext101_32x4d_features import resnext101_32x4d_features,resnext101_32x4d_features_blob __all__ = ['ResNeXt101_32x4d', 'resnext101_32x4d'] pretrained_settings = { 'resnext101_32x4d': { 'imagenet': { 'url': 'http://data.lip...
#!/usr/bin/env python """ Generate a simple scatter plot of power... """ import cgi import sys import datetime import numpy as np import matplotlib.colors as mpcolors import matplotlib.colorbar as mpcolorbar import matplotlib.patheffects as PathEffects from pyiem.meteorology import uv from pyiem.plot.use_agg import ...
# Copyright 2017-present Open Networking Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
from typing import * import numpy as np from itertools import combinations, product, permutations from scipy.special import loggamma def rss_objective( y_test: np.ndarray, y_predicted: np.ndarray) -> float: """Return the residual sum of squares""" return np.sum((y_predicted - y_test)**2) def rmse_objective(...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to assume a role using AWS Security Token Service (AWS STS) credentials. """ import json import time import sys import boto3 from botocore.exceptions import ClientError def progress_bar(...
# SPDX-FileCopyrightText: 2019-2021 REFITT Team # SPDX-License-Identifier: Apache-2.0 """Implements the common `Alert` interface for all broker clients.""" # type annotations from __future__ import annotations from typing import List, Dict, Union, Any, Optional # standard libs import json from datetime import datet...
# CD to DAPPER folder from IPython import get_ipython IP = get_ipython() if IP.magic("pwd").endswith('tutorials'): IP.magic("cd ..") else: assert IP.magic("pwd").endswith("DAPPER") # Load DAPPER from common import * # Load answers from tutorials.resources.answers import answers, show_answer # Load widgets fr...
#!/usr/bin/python import re import sys import os from multiprocessing import Process from utils import * try: from argparse import ArgumentParser except: prettyprint(''' Welcome to the Mod-Lang-Scala Release Script. This release script requires that you use at least Python 2.7.0. It ap...
from back.models import * from pony.orm import db_session from random import choice import back.legacy type_dict = { 'profile':'toone', 'sender':'toone', 'receiver':'toone', 'topic':'toone', 'node':'toone', 'nodemean_node':'toone', 'classrooms':'tomany', 'sentEnvelopes':'tomany', '...
import os.path as op from collections import OrderedDict from six import text_type from datalad.utils import Path from datalad.distribution.dataset import ( rev_get_dataset_root, resolve_path, ) from . import aggregate_layout_version import logging lgr = logging.getLogger('datalad.dataset') # TODO drop wh...
import os from pathlib import Path PATH_LIKE_KWARGS = [ "bids-filter-file", "fs-license-file", "fs-subjects-dir", "work-dir", "w", ] FLAGS = ( "skip_bids_validation", "low-mem", "boilerplate", "longitudinal", "skull-strip-fixed-seed", "no-submm-recon", "fs-no-reconall", ...
from typing import Callable, Union from matplotlib.axes import Axes import torch import torch.nn as nn import numpy as np from models.custom import DentReLUFunction import matplotlib.pyplot as plt import utils import models plt.style.use("classic") def _ax_plot(ax_func: Callable[[Axes], None], name): plt.figure(...
import os import argparse import numpy as np import pandas as pd import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader from read_data import ChestXrayDataSet from model import DenseNet121 from cataly...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Train the model""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import pandas as pd import torch import numpy as np import os import scipy import matplotlib.image as mpimg import torch.nn ...
"""Most rules are described in 'Secrets in Source Code: Reducing False Positives Using Machine Learning'.""" import os.path from abc import ABC, abstractmethod from typing import List, Any import numpy as np from scipy.sparse.csr import csr_matrix from sklearn.preprocessing import LabelBinarizer from credsweeper.com...
from picamera import PiCamera from time import sleep from PIL import Image import argparse import io import numpy as np from fractions import Fraction import datetime import os class Config: def __init__(self, resolution = None, sensor_mode = None, exposure = None, iso = None, exposure_mode = None, rotatio...
import os import torch import pickle import pandas as pd import numpy as np from torch.utils.data import Dataset import tqdm def createDataCSV(dataset): labels = [] texts = [] dataType = [] label_map = {} name_map = {'wiki31k': 'Wiki10-31K', 'wiki500k': 'Wiki-500...
import argparse import contextlib import sys import time import cupy import numpy from black_scholes import black_scholes_kernel # This sample computes call prices for Europian options with # Monte-Carlo simulation. It was based on a sample of the financial package # in CUDA toolkit. For details, please see the corr...
#!/bin/env python """Plot script for uaibus log files.""" from math import atan2, radians, cos, sin, asin, sqrt import click import csv import random import datetime import folium import folium.plugins import logging import numpy as np import sys def distance(lat1, lng1, lat2, lng2): R = 6371000 # raio da terra...
import logging import uuid try: from urllib.parse import urljoin, urlencode, parse_qs # Python 3 except ImportError: from urlparse import urljoin, parse_qs # Python 2 from urllib import urlencode import requests logger = logging.getLogger('moneybird') class Authentication(object): """ Base cl...