text
stringlengths
3.07k
22.1k
"""Module for path (and path-like) object manipulation""" from functools import wraps from dataclasses import dataclass from typing import Union import os from dol.base import Store from dol.util import lazyprop from dol.trans import store_decorator from dol.dig import recursive_get_attr path_sep = os.path.sep @da...
# в этом файле собраны классы всех окон, кроме основного import sqlite3 from random import sample from datetime import timedelta, date from graphics import LOADING from PyQt5.QtChart import QChart, QChartView, QPieSeries from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog, QWidget, QInputDialog from PyQt5...
import torch import torch.nn as nn import math import sys from pydestruct.nn.mlp import MLP from pydestruct.nn.dropout import SharedDropout from pydestruct.nn.transformer import LayerNorm class StandardDependencyModule(nn.Module): def __init__(self, input_dim, proj_dim, ...
""" ################################################## ################################################## ## TODO ## ################################################## ################################################## """ ################### ##### IMPORTS ##### ######...
import argparse import os import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from dataset.dataset import AVDataset from models.basic_model import AVClassifier from utils.utils import setup_seed, we...
import re import shutil import time import os from bzt import ToolError from tests import BZTestCase, RESOURCES_DIR, BUILD_DIR, close_reader_file, ROOT_LOGGER, ExecutorTestCase from bzt.modules.aggregator import DataPoint, KPISet from bzt.modules.grinder import GrinderExecutor, DataLogReader, Grinder, GrinderMirrorsM...
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides utility functions for TCP/UDP echo servers and clients. This program has classes and functions to encode, decode, calculate checksum and ver...
import math import random import torch import torch.nn.functional as F import trajnettools def rotate_path(path, theta): ct = math.cos(theta) st = math.sin(theta) return [trajnettools.TrackRow(r.frame, r.pedestrian, ct * r.x + st * r.y, -st * r.x + ct * r.y) for r in path] def random_rotatio...
""" Code taken and modified from: https://github.com/Adapter-Hub/hgiyt. Credits: "How Good is Your Tokenizer? On the Monolingual Performance of Multilingual Language Models" (Rust et al., 2021) https://arxiv.org/abs/2012.15613 """ import collections import logging import os from dataclasses import dataclass, field from...
''' Simulation... ''' import sys import numpy as np import matplotlib.pyplot as plt from Vehicle import Vehicle import plot_routines as pr import pickle def initialize(): ''' Returns array of vehicles; simulation step length in seconds. ''' dt = 0.05 # seconds total_time = 60 # seconds ...
"""Set up a simple plug-in architecture for Posetta Description: ------------ In order to be able to add readers and writers etc without needing to hardcode names, but rather pick them from the command line or similar, we use a simple plug-in architecture. The plug-in mechanism is based on the different plug-ins regi...
""" Module for defining models to organize the data and options to be tracked. """ import itertools import maya.cmds as mc import pymel.core as pm import utils import ui class Model( object ): """ The base model. """ class Meta: pass def __init__( self ): self.fields = [] ...
## @package field from model.database import Database from model.team import Team from field.driverstationconnection import DriverStationConnection, ListenForDsUdpPackets, ListenForDriverstations, SignalMatchStart from consolelog import * from game import matchtiming from game.matchstate import MatchState from game.sco...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import argparse import logging import os import re import onnx import torch from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import build_detection_test_loader...
"""This processor parses and casts amounts and dates by sniffing data. Assumptions ----------- At this stage we assume that there is only one data resource. Data processing --------------- The processor goes through all fields in the schema and assigns them a caster. If the field has a complete set of format parame...
"""A dash app to plot snapspectra.""" import re import uuid import numpy as np import pandas as pd from functools import lru_cache import dash import dash_daq as daq import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Out...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # Name: caching.py # Purpose: music21 classes for representing score and work meta-data # # Authors: <NAME> # <NAME> # # Copyright: Copyright © 2010, 2012 <NAME> and the music21 # ...
import atexit import functools import logging import os import signal import gevent.lock from monotonic import monotonic import prometheus_client as prom # need to keep global track of what metrics we've registered # because we're not allowed to re-register metrics = {} def timed(name=None, buckets=[10.**x for x...
import logging import time from multiprocessing import Pool from client import huobipro_client, poloniex_client, unified_client from config import config_trader, config_coin logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.WARNING) premium_invalid_threshold = 0.2 clas...
#!/usr/local/bin/python import argparse import os import sys import pandas as pd import numpy as np import time pd.options.mode.chained_assignment = None parser = argparse.ArgumentParser(prog='snvScore') parser.add_argument('SampleBED',type=str,help='Path to the mosdepth per-base BED output') parser.add_argument('SNVG...
"""Wordnet lexicon validation. This module is for checking whether the the contents of a lexicon are valid according to a series of checks. Those checks are: ==== ========================================================== Code Message ==== ========================================================== E101 ID is not...
""" Inspiration: https://github.com/cfedermann/mass-mailer Resources: mimetypes http://naelshiab.com/tutorial-send-email-python/ https://www.anomaly.net.au/blog/constructing-multipart-mime-messages-for-sending-emails-in-python/ https://stackoverflow.com/questions/3902455/mail-multipart-alternative-vs-multipart-mixed/...
#!/usr/bin/env python3 #============================================================================== # tsv-dd-to-html is a very, exceedingly quick and dirty Python script that # takes our tab-separated data dictionary files and puts them into a readable # HTML format with some row-spanning stuff. # # ---<NAME> <<EMA...
import argparse from collections import OrderedDict from datetime import datetime import json import os import sys import jsonschema import requests from service_lib.database import DatabaseEngine from service_lib.config_models import ConfigModels from service_config import ServiceConfig from dataproduct_service_conf...
#!/usr/bin/env python import urwid import urwid.raw_display import urwid.web_display import dialog import os import rosgraph import re from collections import OrderedDict import argparse import socket def sysout(s): # with open('/dev/pts/32', 'a') as f: # f.write(s) # f.write(os.linesep) pas...
"""empty message Revision ID: 8<PASSWORD> Revises: <PASSWORD> Create Date: 2019-05-03 16:00:58.894118 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '8<PASSWORD>' down_revision = '<PASSWORD>' branch_labels = None depen...
# -*- coding: utf-8 -*- """ Created on Thu Sep 19 18:50:24 2019 @author: haukeh """ # -*- coding: utf-8 -*- """ Service functions for reeem_db This file is part of project REEEM (https://github.com/ReeemProject/reeem_db). It's copyrighted by the contributors recorded in the version control history: ReeemProject/ree...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2018 <NAME> """ Functions to support ray tracing a sequential optical model .. Created on Thu Jan 25 11:01:04 2018 .. codeauthor: <NAME> """ import numpy as np from numpy.linalg import norm from math import sqrt, copysign import rayoptics.optical.model_co...
import asyncio import concurrent.futures import contextlib import functools import os import pathlib from typing import Generic, Optional, TypeVar from wcpan.drive.core.drive import ( Drive, download_to_local, upload_from_local, ) from wcpan.drive.core.types import Node from wcpan.logger import EXCEPTION, ...
# Last updated January 23, 2017 """ This module is used for testing python code in CS 116 and CS 234 The useful functions in this module are: * check.within, for testing functions whose output includes floats * check.expect, for testing all other functions * check.set_screen, for testing screen out...
import numpy as np from functools import reduce from itertools import product import utils as ut def factors(n): return set(reduce( list.__add__, ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) def factor_pairs(n): f = factors(n) f_array = np.array(list(f))...
""" This class is intended to be a wrapper around *pexpect*. The reason for implementing such a wrapper is to avoid having several testcases repeating the same sequences of calls to be *pexpect.sendline()* / *pexpect.spawn()* / *pexpect.read()* e.t.c. Furthermore the intention is to protect users from sequences of ca...
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-0236-Lowest-Common-Ancestor-of-a-Binary-Tree.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-03-28 ===========...
# Support for manipulating constraints of the form # SUM (a_i * x_i) >= c # where each a_i is positive or negative integer # x_i is Boolean import sys import getopt import random import queue class ConstraintException(Exception): form = "Constraint Error" msg = "" def __str__(self): m = self.form...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Code for distilling a transformer/generator model. """ from typing import Optional from parlai.core.params import Pa...
#! /usr/bin/env python3 # IDEA: If file with same name already exists in target directory, but file contents are different, then append a number to new filename. # IDEA: Recurse into subdirectories in some reasonable manner. # IDEA: Handle zipfiles in some reasonable manner. # IDEA: Cleanup filenames (URL-decode, remo...
import os import re from collections import namedtuple from datetime import datetime from itertools import count from lib import ( large_static_store, microdata, guess_extension, guess_mimetype, ) COLLATERAL_CREATIONS = 'collateral_creations' DEPENDS_ON = 'depends_on' DEPENDENT_OF = 'dependent_of' #...
''' assignment_utilities.py Assignment manager utilities ''' import datetime import json import random import re import string import time from urllib.parse import parse_qs from flask import g import requests import holidays as pyholidays import pandas as pd from business_duration import businessDuration BEARER =...
import hashlib from datetime import datetime from enum import Enum from typing import Dict, List, Optional, Type, Union from uuid import UUID, uuid4 from pydantic import BaseModel, Field, HttpUrl, conint, validator from ...models.config import BaseConfig from ...models.schemas.files import File from ...models.schemas...
class Board: def __init__(self, grid=None): if grid is None: self.grid = {'00': 0, '01': 0, '02': 0, '03': 0, '10': 0, '11': 0, '12': 0, '13': 0, '20': 0, '21': 0, '22': 0, '23': 0, '30': 0, '31': 0, '32': 0, '33': 0} ...
import hashlib from random import randrange import random import statistics import numpy import secrets from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashe...
from collections import Counter import sys from finntk.wordnet.utils import fi2en_post from nltk.corpus import wordnet import click import re from senseclust.groupings import gen_groupings, gen_multi_groupings, write_grouping, clus_key_clus, synset_key_clus, outer_join, skip_first, filter_grouping_repeats, same_diff_of...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.collections import LineCollection import time """ This code was built just to generate ICE plots for comparison in the paper. We just hacked it together. """ from stratx.partdep import getcats def predict_catice(model, X:pd.DataF...
# Copyright 2014-2016 <NAME> <<EMAIL>> # # 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 import os import shutil import xml.etree.ElementTree as ET import pickle import time from config import DIC_AGENTS, DIC_ENVS def downsample(path_to_log): path_to_pkl = os.path.join(path_to_log, "inter_0.pkl") f_logging_data = open(path_to_pkl, "rb") logging_data = pickle.load(f_logging_data)...
import math import re slugify = lambda x: re.sub('[-\s]+', '-', re.sub('[^\w\s-]', '', x.strip())).lower() def intcomma(orig): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ new = re.sub("^(-?\d+)(\d{3})",...
import re from typing import Optional, List from config import config from p1_utils.data_type import Register from p1_utils.errors import RegisterInvalidError, FieldDspInvalidError, FieldLengthInvalidError, BitsInvalidError, \ RegisterIndexInvalidError from p2_assembly.mac0_generic import LabelReference from p2_as...
# -*- coding: utf-8 -*- u"""PyTest for :mod:`sirepo.template.code_variable.py` :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_cache(): from py...
# -*- coding: utf-8 -* arquivo = open('D:\werik\Google Drive\Faculdade\Décimo Segundo Período\Compiladores 1\FONTE.mgol', 'r') for linha in arquivo: print(linha) arquivo.close() """#Definição do alfabeto Onde iremos definir o alfabeto """ def letra(caractere): return caractere in string.ascii_letters #Todas ...
# Authors: <NAME>, pyscf authors """ This module implements the G0W0 approximation on top of `pyscf.tdscf.rhf_slow` and `pyscf.tdscf.proxy` TD implementations. Unlike `gw.py`, all integrals are stored in memory. Several variants of GW are available: * (this module) `pyscf.gw_slow`: the molecular implementation; * `...
#!/usr/bin/env python """ Generic python script. """ __author__ = "<NAME>-Wagner" import fitsio import numpy as np # galsim.Sersic documentation # http://galsim-developers.github.io/GalSim/classgalsim_1_1sersic_1_1_sersic.html # galsim.Shear documentation # http://galsim-developers.github.io/GalSim/classgalsim_1_1she...
import torch import torch.nn as nn from torch.autograd import Variable from collections import OrderedDict OPS = { 'none' : lambda C, stride, affine, edge: Zero(stride), 'noise': lambda C, stride, affine, edge: NoiseOp(stride, 0., 1.), 'skip_connect' : lambda C, stride, affine, edge: Identity() if stride == 1 el...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import arrow from bs4 import BeautifulSoup import re import dateutil import requests import json # RU-1: European and Uralian Market Zone (Zone 1) # RU-2: Siberian Market Zone (Zone 2) # RU-AS: Russian Far East BASE_EXCHANGE_URL = 'http://br.so-ups.ru/webapi/api/flowDiagra...
import builtins import os import stat import pytest from zulipterminal.cli.run import ( THEMES, _write_zuliprc, exit_with_error, get_login_id, in_color, main, parse_args, ) from zulipterminal.model import ServerConnectionFailure from zulipterminal.version import ZT_VERSION @pytest.mark.p...
#! /usr/bin/env python3 import argparse import sys import os import re import shutil class FileObject: def __init__(self, abs_file_name, media_file=True): if not os.path.isfile(abs_file_name): raise FileNotFoundError('%s is not a valid file' % abs_file_name) self._abs_file_name = abs...
""" One table verb implementations for a :class:`pandas.DataFrame` """ import warnings import numpy as np import pandas as pd from ..types import GroupedDataFrame from ..options import get_option from ..operators import register_implementations from ..utils import Q, get_empty_env, regular_index from .common import E...
"""A class with a number of generic pre-defined (magic) methods inspired by dataclass of Python 3.7. Index ----- .. currentmodule:: assertionlib.dataclass .. autosummary:: AbstractDataClass AbstractDataClass.__repr__ AbstractDataClass.__eq__ AbstractDataClass.__hash__ AbstractDataClass.__copy__ ...
"""Lempel-Ziv complexity-based distance Computing distances between DNA/protein sequences based on the Lempel-Ziv complexity (LZ complexity). LZ complexity of a finite sequence S is related to the number of steps required by a production process that builds S. References: 1. <NAME>, Ziv. (1976) IEEE Transactions...
#!/usr/bin/env python3 import copy import unittest import plato_pylib.utils.supercell as tCode import plato_pylib.shared.ucell_class as UCell class testCreateSuperCells(unittest.TestCase): def setUp(self): fractCoordsA = [ [0.0,0.0,0.0,"Mg"], [0.33333333, 0.33333333, 0.5, "Mg"] ] origLattVectsA = [ [6.06, 0.00...
import datetime import json from google.cloud import iot_v1 from flask import Blueprint, request, redirect from utilities.pubsub_functions import pub_admin_scripts, pub_manage_server from utilities.globals import ds_client, project, log_client, compute, zone, LOG_LEVELS, AdminActions, workout_globals from utilities.yam...
from __future__ import annotations from abc import ABC, abstractmethod from math import inf, pi from typing import ClassVar, Union from ..constants import c as speed_of_light, G as Newton_G from ..math import complexify, csinc, log10, realise, sinc from ..quantities.quantity import GenericQuantity from ..units.angula...
import os import numpy as np import pandas as pd import pytorch_lightning as pl from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import LabelEncoder import torch import src.config as proj_config class EventDataset(Dataset): @staticmethod def get_embeddings_vec(events, feature_name):...
# =============================================================================== # Copyright 2015 <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 pyqmc.slater as slater import pyqmc.multiplywf as multiplywf import pyqmc.addwf as addwf import pyqmc.jastrowspin as jastrowspin import pyqmc.func3d as func3d import pyqmc.gpu as gpu import numpy as np import h5py def generate_slater( mol, mf, optimize_determinants=False, optimize_orbitals=Fals...
""" Transform contains structures helpful for writing analysis and transformation passes over blocks. Most of the functions in this module are for advanced users only. However, the following functions are prebuilt transformations that everyone can use: (As of 7/1/16 there are none in this folder). Other user accessib...
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ Analist site views """ __author__ = "<NAME> (<EMAIL>)" __copyright__ = "Copyright 2014, <NAME>" __license__ = "MIT (http://opensource.org/licenses/MIT)" import logging log = logging.getLogger(__nam...
""" This preprocesing script parses annotated relations and entities from the prodigy jsonln output files. Also includes splitting functions. """ import json, random, os, ast from spacy.tokens import DocBin, Doc from spacy.vocab import Vocab from wasabi import Printer def merge_jsonl(jsonl_dirs, output_path): """M...
""" contain all the functions """ from os import times import ParaScript as ps import matplotlib.pyplot as plt #TODO: # 1. add fixed operation cost # 2. add the effect of freqeuncy class OperatorClass(object): """ operator """ def __init__(self, _id): self.id = _id self.price ...
import os import math import sys import time import a3dc_module_interface as a3 import numpy as np from modules.packages.a3dc.ImageClass import ImageClass from modules.packages.a3dc.constants import NUMERIC_DTYPES from modules.a3dc_interface import colocalization, apply_filter, save_data, save_image from modules.a3d...
import os from typing import Set, List, Dict import secrets import logging import http import json import ssl import time from datetime import datetime, timedelta from enum import Enum, auto from collections import defaultdict import requests from flask import Flask from flask_sockets import Sockets import gevent from...
# -*- coding: utf-8 -*- """ Created on 2019-11-26 16:40 @author: a002028 """ import os import time import pandas as pd from algaware.core.datahandler import DataHandler from algaware.core.statistics import StatisticsHandler from algaware.core.config import Settings from algaware.plot import plot as alg_plot class...
import collections import importlib import pprint import logging import pathlib from qtpy.QtWidgets import * from qtpy.QtCore import * from qtpy.QtGui import * from qtpy import QtCore, QtGui, QtWidgets from .. import gui, config from .laystruct import LayoutStruct from .dockwidgets import DockContainer, DockTab, Dock...
# Basics of Python # types of data in python3 def types_of_data(): # _____________Types of data in python3____________________ # strings-anything between "________" or this '_____________' is known as string a = "" print(type(a)) # Lists-anything between [_________] is called list l = [] ...
import copy import time import calendar from datetime import timedelta, datetime as Datetime import pytz import pytest import maya from maya.core import _seconds_or_timedelta # import private function @pytest.mark.parametrize("string,expected", [ ('February 21, 1994', 'Mon, 21 Feb 1994 00:00:00 GMT'), ]) ...
#!/usr/bin/env python3.6 import pandas as pd import logging import string import re import csv import sys from modules import * #---01--- # Block for working with some files ------------------------------ def read_xlsx(filename): # special for XLSX try: array = pd.read_excel(filename, engine='openpyxl') logg...
""" Shake-Shake-ResNet for CIFAR, implemented in PyTorch. Original paper: 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485. """ __all__ = ['CIFARShakeShakeResNet', 'shakeshakeresnet20_2x16d_cifar10', 'shakeshakeresnet20_2x16d_cifar100', 'shakeshakeresnet26_2x32d_cifar10', 'shakeshakere...
from sys import platform from copy import copy from waapi.client.event import EventHandler from waapi.client.interface import UnsubscribeHandler from waapi.client.executor import SequentialThreadExecutor from waapi.wamp.interface import WampRequest, WampRequestType, CannotConnectToWaapiException, WaapiRequestFailed fr...
# -*- coding: utf-8 -*- """Views to run and serve actions.""" from typing import Optional from django import http from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from django.shortcuts import redirect, render from django.urls import reverse from django.ut...
""" 2013 May 13 <NAME> Purpose: Take an input uv fits file and replace or subtract the visibilities with a model for the surface brightness map of the target. Inputs: sbmodelloc: location of fits image of model for surface brightness map visdataloc: location of uv fits data for target Outputs: vismodel: ...
from . import stacktrace import warnings import ast import textwrap import functools import inspect from dataclasses import dataclass from typing import Optional @dataclass class Variable: name : str type : Optional[str] = None def __str__(self): if self.type: return f"?{self.name} - {s...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import math from scipy import stats # class to get the data, clean it, format it class process_data: def __init__(self, url, delim): self.url = url self.delim = delim def get_data(self): data =...
import numpy as np import numpy.testing as npt import fury.primitive as fp import math def test_vertices_primitives(): # Tests the default vertices of all the built in primitive shapes. l_primitives = [(fp.prim_square, (4, 3), -.5, .5, 0), (fp.prim_box, (8, 3), -.5, .5, 0), ...
# Copyright 2015, Pinterest, 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...
import typing from collections import OrderedDict from functools import partial, reduce from operator import xor from typing import Any, Generator, Hashable, TYPE_CHECKING, Union from bitarray import bitarray if TYPE_CHECKING: BaseDict = OrderedDict[Hashable, Any] else: BaseDict = OrderedDict from_bytes = pa...
import os, asyncio, random, discord, json, requests, re, datetime, helper from dotenv import load_dotenv from discord.ext import commands load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix='b!') @bot.event async def on_ready(): print(f'{bot.user.name} has connected to Discord!') @...
#!/usr/bin/env python # ---------------------------------------------------------------------- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the ho...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys from textwrap import dedent from clint.textui import indent from commcare_cloud.alias import commcare_cloud from commcare_cloud.cli_utils import ask, check_branch from commcare_cloud.colors ...
# Copyright 2019–2020 Leibniz Institute for Psychology # # 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, ...
import json import re from collections import OrderedDict from pathlib import Path import csv from datetime import datetime from capdb.models import Citation, CaseMetadata, EditLog from scripts.helpers import alphanum_lower """ How to run this script: * Test run: fab run_script:scripts.citation_clea...
import torch import torch.nn as nn __all__ = ['resnet8', 'resnet14', 'resnet20', 'TestCNN'] def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, g...
"""Defines task datasets. A task is a mapping from one or more word representations to linguistic features. The datasets """ import logging import pathlib from typing import Any, Iterator, Optional, Sequence, Tuple from ldp.utils.typing import Device, PathLike import h5py import torch from torch.utils import data D...
from tweepy.streaming import StreamListener from tweepy import OAuthHandler, Stream from tweepy.api import API from discordWebhooks import Webhook, Embed, Field import calendar, datetime, time, random, json from time import gmtime, strftime from datetime import datetime import html import logging import requests.packag...
from engine.query import search from test_data import util from math import log import pickle import json def precision_at_k(k, num_relevant, query, search_type, operation_type, incorporate_pr, test_set,input=False): ''' :param k: number of retrieved documents :param query: :param search_type: :par...
import os import sys import time import pickle import argparse import tabulate import numpy as np import autosklearn.classification from sklearn.metrics import balanced_accuracy_score sys.path.append(os.getcwd()) from mindware.estimators import Classifier from mindware.datasets.utils import load_train_test_data from m...
import torch import torch.nn as nn OPS = { 'mbconv_k3_t1': lambda C_in, C_out, stride, affine, track_running_stats: MBConv(C_in, C_out, 3, stride, 1, t=1, affine=affine, track_running_stats=track_running_stats), 'mbconv_k3_t3': lambda C_in, C_out, stride, affine, track_running_stats: MBConv(C_in, C_out, 3, str...
# encoding: utf-8 """ capability/__init__.py Created by <NAME> on 2012-07-17. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ # =================================================================== Capability # from exabgp.bgp.message.notification import Notify class Capability (object): class ID (i...
# -*- coding: utf-8 -*- """ readability.clients ~~~~~~~~~~~~~~~~~~~ This module provies a client for the Reader API. """ import json import logging import urllib import oauth2 import httplib2 from .utils import filter_args_to_dict logger = logging.getLogger(__name__) DEFAULT_READER_URL_TEMPLATE = 'https://www.r...
# Copyright 2018-2021 Xanadu Quantum Technologies 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 applicabl...
import copy import numpy as np import sklearn.model_selection from ..core import MODEL_TYPE_CLASSIFICATION from ..core.config import CONFIG_CROSS_VALIDATION from .datasets_base import DatasetsBase, InOut from ..util.mem import memory CV_METHODS = ['KFold', 'RepeatedKFold', 'LeaveOneOut', 'LeavePOut', 'ShuffleSplit',...