text
stringlengths
3.07k
22.1k
""" Module for evaluation of decision rule explanations. """ import numpy as np from teex._utils._errors import MetricNotAvailableError from teex.decisionRule.data import DecisionRule, rule_to_feature_importance, Statement from teex.featureImportance.eval import feature_importance_scores _AVAILABLE_DECISION_RULE_MET...
import math from typing import Union from tensorflow.keras import layers, Model CONV_KERNEL_INITIALIZER = { 'class_name': 'VarianceScaling', 'config': { 'scale': 2.0, 'mode': 'fan_out', 'distribution': 'truncated_normal' } } DENSE_KERNEL_INITIALIZER = { 'class_name': 'Varianc...
from operator import mul, add from functools import reduce from sympy.core import Basic from sympy import Symbol from sympy.core import Expr from sympy import Function from sympy.core.singleton import S from sympy.core import Add, Mul...
import random import torch import numpy as np PAD, UNK, BOS, EOS = '<pad>', '<unk>', '<bos>', '<eos>' BOC, EOC = '<boc>', '<eoc>' LS, RS, SP = '<s>', '</s>', ' ' CS = ['<c-1>'] + ['<c' + str(i) + '>' for i in range(32)] # content SS = ['<s-1>'] + ['<s' + str(i) + '>' for i in range(512)] # segment PS = ['<p-1>'] + ['<...
import unicodedata import jsonlines import re from urllib.parse import unquote import regex import numpy as np import scipy.sparse as sp from sklearn.utils import murmurhash3_32 def normalize(text): """Resolve different type of unicode encodings / capitarization in HotpotQA data.""" text = unicodedata.normaliz...
""" Linking errors from logfiles to each other """ import os import numpy as np import re from datetime import datetime def merge_all_errors_by_time(all_errors, fields_names): all_messages = [] set_headers = set([h for s in list(fields_names.values()) for h in s]) set_headers.remove...
import os import sys import cv2 import argparse import numpy as np import logging import torch from torch import nn from torch.nn import MSELoss from torch.optim import Adam import torch.nn.functional as F from torch.optim.lr_scheduler import MultiStepLR from torch.utils.data import DataLoader from tensorboardX impor...
""" Compare COVID-19 simulation outputs to data. Estimate Rt using epyestim """ import argparse import os import pandas as pd import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import sys import matplotlib.dates as mdates import epyestim import epyestim.covid19 as covid19 import seaborn as sns sy...
"""Internal library for admin.""" import ipaddress import logging import random import string from functools import wraps from itertools import chain import dns.resolver from dns.name import IDNA_2008_UTS_46 from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.utils.e...
# %pip install contractions # %pip install inflect # %pip install plotly # %pip install emoji # %pip install emot import os import re import json import pickle import string import pandas as pd import seaborn as sns import nltk import datetime import wordcloud import matplotlib.pyplot as plt import re import unicodeda...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
""" Definition of all repository models. """ from enum import Enum from typing import Optional, List from typing_extensions import Literal from pydantic import BaseModel, SecretStr class PackageTypeEnum(str, Enum): """Enumerates package types.""" maven = "maven" gradle = "gradle" ivy ...
from __future__ import absolute_import yt = None # deferred import; occurs when a YtInputHandler is constructed from . import finding from . import HandlerBase from .. import config from ..log import logger from six.moves import range import numpy as np class YtInputHandler(finding.PatternBasedFileDiscovery, Handler...
"""The Fronius integration.""" from __future__ import annotations import asyncio from collections.abc import Callable import logging from typing import TypeVar from pyfronius import Fronius, FroniusError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION,...
"""Metrics to assess under- and over-fitting of systematic noise. This module provides two metrics, `overfit_metric_lombscargle` and `underfit_metric_neighbors`, which enable users to assess whether the noise in a systematics-corrected light curve has been under- or over-fitted. These features were contributed by <NA...
""" Functions related to dataset handling Main function: convert the dataset to TFRecord File """ import json import tensorflow as tf import skimage.io from image2source.common_definitions import ( IMAGE_INPUT_SIZE, BUFFER_SIZE, TOP_K, MAX_SEQ_LEN_DATASET, N_TEST_DATASET, BATCH_SIZE) from image2source.utils impo...
#!/bin/env python """ The server DL code for the hierarchical level instrumentation author: <NAME> NIH\LCP data: Sept 2018 - Nov 2 2018 The server has the basic set of functions: 0) init 1) close 2) abort 3) subscribe (on/off) 4) snapshot 5) task 6) """ __version__ = "0.0.0" __date__ = "January 20, ...
#!/usr/bin/env python3 """Create trendbargraphs of the data for various periods.""" import argparse from datetime import datetime as dt import sqlite3 as s3 import pandas as pd import matplotlib.pyplot as plt import numpy as np import constants DATABASE = constants.TREND['database'] TABLE_RHT = constants.TREND['sq...
"""WEBSAW - a web framework for rapid development with pleasure""" import os import code import click import sys import platform import json import pydal import zipfile import signal import asyncio import logging import ombott import inspect from .watcher import watch # Optional web servers for speed try: import...
import os import math import torch import shutil import logging import transformers from datasets import load_dataset import pandas as pd import numpy as np from theconf import Config as C from transformers import BertForSequenceClassification, Trainer, TrainingArguments, BertTokenizerFast import joblib try: from ...
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .types import Permission as PermissionTuple __all__ = ( "ChannelPermissions", "ServerPermissions" ) # Channel permissions # # View = 0b00000000000000000000000000000001 // 1 # SendMessage = 0b000...
from dataclasses import dataclass import typing from typing import Iterable import abc import pipeline_dp from pipeline_dp.aggregate_params import Metrics from pipeline_dp.pipeline_operations import PipelineOperations from pipeline_dp.accumulator import Accumulator, CompoundAccumulator @dataclass class SketchParams:...
# -*- coding: utf-8 -*- import os from copy import copy from collections import OrderedDict import yaml from jinja2 import Environment, FileSystemLoader j2 = Environment( loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")), trim_blocks=True, lstrip_blocks=True ) from errors impor...
from argparse import ArgumentParser import os import pickle import re from datetime import datetime from typing import * from bs4 import BeautifulSoup from linebot import LineBotApi from linebot.exceptions import LineBotApiError from linebot.models import TextSendMessage from requests import * class Co...
import sys import uuid from dataclasses import dataclass from dataclasses import field from dataclasses import fields from dataclasses import make_dataclass from typing import Dict from typing import get_type_hints from typing import Iterator from typing import List from typing import Union from unittest import mock fr...
import socket import socket import sys import os from tradutor import tradutor_main, translate_sentence from _thread import start_new_thread import json import os import traceback from http.server import BaseHTTPRequestHandler, HTTPServer import socketserver import ssl # from flask import Flask # f...
from rest_framework.test import APIClient from django.test import TestCase, TransactionTestCase from authors.apps.authentication.models import User class BaseTest(TestCase): def setUp(self): self.user_data = {"user": {"username": "Jacob1234", "email": "<EMAIL>", ...
#! /usr/bin/env python ''' Author: <NAME> Based on paper, A SOFTWARE FRAMEWORK FOR MUSICAL DATA AUGMENTATION <NAME>, <NAME>, and <NAME> https://bmcfee.github.io/papers/ismir2015_augmentation.pdf ''' from __future__ import print_function import numpy as np import librosa from random import getrandbits import sys, geto...
from xmlr import xmliter from Entities.Post import Answer, Question from config import RECORD_NUM, PARSER_PKL, CACHE from utility.datetime_util import str2dt from collections import defaultdict import pickle import os class PostParser: """ This class is used for reading the post file. It reads it record b...
""" Metaheuristic Minimization Using Particle Swarm Optimization. Copyright (c) 2021 <NAME> """ import numpy as np def PSO(func, LB, UB, nPop=40, epochs=500, K=0, phi=2.05, vel_fact=0.5, conf_type='RB', IntVar=None, normalize=False, rad=0.1, args=[], Xinit=None): """ func Function...
# -*- coding: utf-8 -*- # Copyright 2016 Open Permissions Platform Coalition # # 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 ...
import tensorflow as tf import numpy as np import math import time from pixel_cnn_pp.nn import * def lrelu(x, rate=0.1): # return tf.nn.relu(x) return tf.maximum(tf.minimum(x * rate, 0), x) def fc_lrelu(inputs, num_outputs): fc = tf.contrib.layers.fully_connected(inputs, num_outputs, ...
# coding: utf-8 """ brownie.tests.terminal ~~~~~~~~~~~~~~~~~~~~~~ Tests for :mod:`brownie.terminal`. :copyright: 2010-2011 by <NAME> :license: BSD, see LICENSE.rst for details """ from __future__ import with_statement import os import sys import codecs import textwrap from StringIO import StringIO...
# # Copyright (c) 2019 MagicStack Inc. # All rights reserved. # # See LICENSE for details. ## import json import random import sqlalchemy as sa import sqlalchemy.orm as orm from sqlalchemy.ext import baked import _sqlalchemy.models as m engine = None session_factory = None bakery = baked.bakery() INSERT_PREFIX = 'i...
# Copyright 2019 NEC Corporation # # 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 writi...
# ciphers.py # # Copyright (C) 2006-2019 wolfSSL Inc. # # This file is part of wolfSSL. # # wolfSSL 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 2 of the License, or # (at your option) any la...
from __future__ import absolute_import, division, print_function import numpy as np from datashape import dshape, isnumeric, Record, Option, DataShape, maxtype from datashape import coretypes as ct from toolz import concat, unique, memoize, identity from .utils import ngjit # Dynd Missing Type Flags _dynd_missing_t...
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * '''IMPORTS''' import re import json from datetime import datetime, date import urllib3.util # Disable insecure warnings urllib3.disable_warnings() def parse_tag_field(tags_str): tags = [] regex = re.compile(r...
import keras from keras.models import Sequential from keras.layers import Dense, Flatten from keras.layers import Conv2D, MaxPooling2D from PIL import Image import numpy as np import mss import random import time import sys from percentages import get_percents from inputfuncs import press, set_stick, release_everything...
# ---------------------------------------------------------------------------- # Copyright (c) 2019--, gemelli development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # -----------------------------------------------...
import re from sqlalchemy import types as sqltypes from sqlalchemy.dialects.postgresql.base import PGDialect from sqlalchemy.dialects.postgresql import INTERVAL from sqlalchemy.engine import reflection from sqlalchemy.schema import CreateColumn from sqlalchemy.ext.compiler import compiles # From Postgresql 10 IDENTIT...
from collections import Iterable, deque from functools import partial from itertools import (chain, combinations, cycle, dropwhile, islice, repeat, starmap, takewhile, tee) from operator import add, attrgetter, itemgetter from sys import version_info from .func import F from .op import flip from...
import torch import pdb from utils.learning import pick_valid_points from utils.io import safe_printout def get_cam_mat(width, height, focal_length): """ Get intrinsic camera matrix (tensor) """ cam_mat = torch.eye(3) cam_mat[0, 0] = focal_length cam_mat[1, 1] = focal_length cam_mat[0, 2] ...
from binascii import hexlify, unhexlify from eth_hash.auto import keccak from os import urandom from secp256k1 import Secp256k1, SECRET_KEY_SIZE, PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE_COMPRESSED, \ EC_COMPRESSED, EC_UNCOMPRESSED from ._libsecp256k1 import ffi, lib class SecretKey: def __init__(self): # Byt...
import asyncio import configparser import logging import os import os.path import random import traceback from pathlib import Path from typing import Dict, Optional from aiohttp import web from . import audios, graphite_statistics, phrases, quest, sessions, utils logging.basicConfig(level=logging.DEBUG) logging.info...
import re import threading import concurrent.futures import time from datetime import datetime from flask import render_template, request, Blueprint, jsonify, url_for, flash, session, redirect, current_app from flask_login import current_user from flask_mail import Message from ..models import Item, ItemClass, ItemDepa...
#!/usr/bin/env python """ Author: <NAME> Email: <EMAIL> """ import os, sys, warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' warnings.filterwarnings('ignore') import argparse, glob, pickle, time, GPUtil, numpy as np from scipy.cluster.vq import whiten as normalise from multiprocessing.managers import BaseManage...
''' This file controls the input for the OCR. Bundles in tkinter and OpenCV using the provided template for the barebones stuff. https://github.com/VasuAgrawal/112-opencv-tutorial/blob/master/opencvTkinterTemplate.py I refered to multiple tutorials / StackOverflow answers online to learn this. Contouring/Thresholding ...
import yaml import requests import os import time import pandas as pd from pandas.core.frame import DataFrame import plotly.express as px import plotly.graph_objects as go import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import updateData ...
# ===================================================================================================================== # Stock exchange data downlaod and experiments # 14.11.2021, <NAME> # ===================================================================================================================== import os,...
import numpy as np from datetime import datetime import copy import roxar_api_utils.ioutil #--------------------------------------------------------------------------------------- # ProfilesVector class class ProfilesVector: """Class for storing a single Profiles vector Args: keyword (str...
# -*- coding: utf-8 -*- import argparse import sys from enum import Enum from pathlib import Path from typing import List, Optional import pydantic import yaml from rich.console import Console from PyR3.construct.mp import MeshProject from PyR3.meshlib import ( LibraryManager, get_paths_from_env, get_path...
from __future__ import annotations import warnings from collections import defaultdict from dataclasses import dataclass from inspect import signature from typing import TYPE_CHECKING, Callable, Dict, List, Set, Tuple, Union from .interactions import Shortcut from .key_bindings import KeymapProvider from .translation...
import json import os from typing import Any, Dict, Iterable, List, Optional, Union from determined import gpu DEFAULT_RENDEZVOUS_INFO_PATH = "/run/determined/info/rendezvous.json" DEFAULT_TRIAL_INFO_PATH = "/run/determined/info/trial.json" DEFAULT_RESOURCES_INFO_PATH = "/run/determined/info/resources.json" DEFAULT_C...
"""A file for the camera class""" import cv2 import time import threading import pyvirtualcam import numpy as np from .constants import sample_length from .args import make_parser class Camera: """Camera class for streaming and taking pictures either from a video or webcam""" def __init__( self, ...
import math import random from ai.state_functions import start_state def pick_move_helper(element): """ Key to be used in pick move helper :param element: An element in the list of moves and their associated statistics: (move, stat) stat is a list of the plays and wins: [plays, wins] ...
#%% from matplotlib import scale import matplotlib.pyplot as plt import numpy as np from scipy import signal import pathlib import pandas as pd from pros_noisefiltering.Graph_data_container import Graph_data_container # FS=500_000 #Sampling frequency in Hz # Define function for Filter freq response #Define a func...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import shlex import ...
import text_process import os import sys import gzip import json import argparse import itertools import _thread import threading sys.path.append(os.getcwd()) import pandas as pd import numpy as np def get_df(path): """ Apply raw data to pandas DataFrame. """ idx = 0 df = {} g = gzip.open(path, 'rb...
r''' Euler angle rotations and their conversions for Tait-Bryan zyx convention See :mod:`euler` for general discussion of Euler angles and conventions. This module has specialized implementations of the extrinsic Z axis, Y axis, X axis rotation convention. The conventions in this module are therefore: * axes $i, j,...
bl_info = { "name": "Import CityJSON files", "author": "<NAME>", "version": (1, 0), "blender": (2, 80, 0), "location": "File > Import > CityJSON (.json)", "description": "Visualize 3D City Models encoded in CityJSON format", "warning": "", "wiki_url": "", "category": "Import-Export",...
#!/usr/bin/env python # coding=utf-8 # creater: <NAME> # date: 2017-05-17 """Switch Gregorian date to day of year, GNSS calendar (GPS & BDS).""" from __future__ import print_function from __future__ import division import datetime __all__ = [ 'GPS_START_DATE', 'BDS_START_DATE', 'bdswd2date', 'bdswd2yrdoy', ...
from django.db import models from django.contrib.auth.models import User from microdata.models import Device, Appliance from django.conf import settings from recurrence.fields import RecurrenceField from paintstore.fields import ColorPickerField # Create your models here. class EventNotification(models.Model): """...
''' Code Challenge: Implement ConvolutionCyclopeptideSequencing. Input: An integer M, an integer N, and a collection of (possibly repeated) integers Spectrum. Output: A cyclic peptide LeaderPeptide with amino acids taken only from the top M elements (and ties) of the convolution of Spectrum that fall bet...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: creators :Synopsis: REST APIs for retrieving and normalizing names of creators of data packages in the EDI data repository. To get all creators' names: GET creators/names Response is a list in JSON format: ["<NAME>","<NAME>"...
#!/usr/bin/env python3 ''' Takes only 1 file as input and do: 1. Quality Check -> reject or continue 2. Filter Badallele ''' MIN_CLUSTER_COVERAGE = 0.8 MIN_COUNT_SNP = 10000 usable_genotypes = set(['A', 'C', 'G', 'T', 'D', 'I']) import os import sys import argparse import gzip import time from collections import C...
from struct import calcsize, pack, unpack, error as UnpackError from socket import inet_aton, inet_ntoa from urlparse import urlunsplit from twisted.internet import (error as netErr, interfaces as netInterfaces, protocol, reactor) from twisted.internet.defer import Deferred, inlineCallbacks, returnValue from ...
"""@file Common.py **Common.py** is a common definitions file this file is imported in almost all others files of the program """ import re import math import time import inspect import struct import weakref try: from queue import Queue except: from Queue import Queue import uuid import sys from nine import ...
# adding some initial comments to test git # one more change here. Messing with git commits on local machine. import requests import json import pandas as pd import numpy as np import time import random import re import os #NLTK import nltk from nltk.corpus import stopwords from nltk.stem import PorterStemmer, WordN...
from collections import defaultdict from typing import TYPE_CHECKING, Dict, Iterable, List, Optional import graphene from django.core.exceptions import ValidationError from ...core.exceptions import InsufficientStock from ...order.error_codes import OrderErrorCode from ...order.utils import get_valid_shipping_methods...
# coding=utf-8 # Copyright 2021 The Google Research 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 applicab...
#-*- encoding: utf-8 -*- from collections import OrderedDict from corpuscula import Conllu import glob import os import re import sys import time from toxine.text_preprocessor import TextPreprocessor from _utils_add import _path, _sub_idx, DATA_DIR_NAME, \ convert_doc, convert_html, convert_odt...
import asynctest from unittest import mock from beacon_api.api.query import transform_record, transform_misses from beacon_api.api.genomic_query import transform_record as transform_record_region from beacon_api.api.genomic_query import transform_misses as transform_misses_region from .test_db_load import Connection ...
""" Created on Mon Feb 11 14:34:02 2019 Converts images data to TFRecords of TF-Example protos. This module reads the files and creates two TFRecord datasets: one for train and one for test. Each TFRecord dataset is comprised of a set of TF-Example protocol buffers, each of which contain a single image and label. th...
#!/usr/bin/env python import logging cache = {} def coordinate(ip_info): return [float(ip_info['Lng']), float(ip_info['Lat'])] class Point(object): def __init__(self, ip_info, **properties): for network in ip_info['Networks']: properties['AS{}'.format(network['ASN'])] = network['ASName...
import numpy as np from scipy.linalg import toeplitz from numpy.fft import rfft, rfftn, irfft, irfftn from numba import njit from . import jacobian as jac from . import determinacy class AsymptoticTimeInvariant: """Represents the asymptotic behavior of infinite matrix that is asymptotically time invariant, giv...
import asyncio import io import json import math import zipfile from collections import Counter from typing import Union import discord from discord.ext import commands from ..bot import Menel from ..utils import embeds, markdown from ..utils.context import Context from ..utils.misc import Timer from ..utils.text_too...
import cv2 import os from typing import Callable, List from datetime import datetime def decode_fourcc(cc): """ Turns the float into a four letter codec string. Taken from here: https://stackoverflow.com/a/49138893/4698227 :param cc: the codec as float :type cc: float :return: the codec st...
#!/usr/bin/env python3 import sys, argparse, numpy, math import scipy.stats as scipystats import matplotlib.pyplot as pyplot parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-infile', '--input-tsv-file', type=str, help='Input TSV file', required=True, de...
import math from travertino.colors import WHITE from toga.widgets.canvas import Context, FillRule from toga_winforms.colors import native_color from toga_winforms.libs import ( Drawing2D, FillMode, GraphicsPath, Matrix, Pen, PointF, RectangleF, SolidBrush, StringFormat, WinForm...
import json import os import re from copy import deepcopy from functools import partial from threading import Event, Thread from time import time, sleep from clearml import Task from typing import Optional, Dict, Any, Iterable from prometheus_client import Histogram, Enum, Gauge, Counter, values from kafka import Kaf...
import signal from howdy import signal_handler signal.signal( signal.SIGINT, signal_handler ) import logging, os, re, time from itertools import chain from multiprocessing import Pool from argparse import ArgumentParser # from howdy.core import core_deluge, core from howdy.tv import tv_torrents, tv def get_items_eztv_...
# -*- coding: utf-8 -*- """ Created on Mon Aug 29 10:59:36 2016 Validation script @author: djp42 """ import os import sys sys.path.append(os.environ["INTENTPRED_PATH"]) import numpy as np from utils import constants as c from utils import data2_class as dd2 from utils import data_util as du from utils import vehicle...
# Copyright(c) 2018 Kenji.Ogura # License: Such as Unauthorized use is prohibited. # mailto : <EMAIL> from mvnc import mvncapi as mvnc import sys import numpy import cv2 import time import csv import os import argparse import sys from sys import argv from g_detector import * from g_camera import * from video_objects...
#_*_ coding=utf-8 _*_ import numpy as np import os, sys from sklearn.datasets import make_moons,load_digits import matplotlib.pyplot as plt import matplotlib.image as mpimg from activation_functions import relu,sigmoid,relu_backward,sigmoid_backward,tanh,tanh_backward,softmax,one_hot from mini_batches import ran...
""" Interface to invert_quda.h """ __all__ = [ "solve", "Solver", ] from functools import wraps from warnings import warn from lyncs_cppyy import nullptr, make_shared from .dirac import Dirac, DiracMatrix from .enums import ( get_inverter_type, get_inverter_type_quda, get_precision, get_precis...
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression import numpy as np import random import pandas as pd from sklearn.metrics import confusion_matrix, f1_score, roc_curve, auc, accuracy_score import joblib from collections import Counter from sklearn.model_selection i...
# coding=utf8 import logging logger = logging.getLogger(__name__) import struct import sys import argparse from bitarray import bitarray import audiogen import afsk def bit_stuff(data): count = 0 for bit in data: if bit: count += 1 else: count = 0 yield bit # todo: do we stuff *after* fifth '1' or ...
# Copyright 2010-2012 Institut Mines-Telecom # # 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 agre...
import sys from importlib import import_module import numpy as np import pandas as pd import pandas._testing as tm import pytest from numpy.testing import assert_array_equal from pandas.testing import assert_frame_equal from pandas.testing import assert_series_equal from hcrystalball.exceptions import InsufficientDat...
import random import torch from torch import nn import numpy as np from .amr_graph import read_file from .vocabs import PAD, UNK, DUM, NIL, END, CLS # Returns cp_seq as a list of lemma + '_' and mp_seq is a list of the lemmas # plus the dictionaries to convert the tokens to an index # This represents the potent...
""" File: P1_utility_functions.py Utility functions used in Phase 1 Pre-processing of the raw chat (.csv) file """ import os.path import re import nltk import gensim from nltk.stem import WordNetLemmatizer def getStopWords(stopWordFileName): """Reads stop-words text file which is assumed to have o...
import numpy as np class Moment: """A class for keeping info about the moments""" def __init__(self, x_true, x_pred,t,index_all,x_static,args,player_ids, player_names, player_jerseys,team_O,team_D,quarter,CF=False): n_playersxy = args.x_dim_permuted-2 if not args.vel else args.x_dim_permuted-4 # 4 ...
""" running Random Forest algorithm on features selected by feature importance """ from __future__ import print_function from time import time import itertools from pprint import pprint as p import numpy as np import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklear...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 25 14:49:50 2018 @author: abhijay """ # Comment import os if not os.path.exists('Q14_plots'): os.mkdir('Q14_plots') #os.getcwd() #os.chdir("/home/abhijay/Documents/ML/hw_1/11632196/") import matplotlib.pyplot as plt import pandas as pd import...
# 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. """STLF forecasting model This model starts from decomposing the time series data with STL decomposition then it fits individual foreasting mod...
from logging import getLogger from shapely.geometry import Point, Polygon, shape, box, LineString from shapely import speedups from geopy import Nominatim from pogeo import get_distance if speedups.available: speedups.enable() class FailedQuery(Exception): """Raised when no location is found.""" class Lan...
#!/usr/bin/env python3 """ Create dataset of "Europeans" with realistic LD structure, based on the out-of-Africa model. Note that the only resemblance to Europeans is in the effective sample size. The recombination rate is constant across the region of nucleotides simulated. LD does not actually resemble real European ...
from datetime import datetime, timedelta from django.test import SimpleTestCase, TestCase from corehq.apps.domain.shortcuts import create_domain from corehq.apps.reports.views import get_scheduled_report_response from corehq.apps.saved_reports.models import ReportConfig, ReportNotification from corehq.apps.saved_repo...
from __future__ import print_function import os import pickle as pk import numpy as np from lensit.pbs import pbs from lensit.misc.misc_utils import npy_hash from lensit.sims import ffs_phas, sims_generic from lensit.ffs_deflect import ffs_deflect verbose = False def get_fields(cls): fields = ['p', 't', 'e', '...