text
stringlengths
3.07k
12.6k
from os import path as osp import numpy as np from multiworld.core.image_env import ImageEnv from railrl.core import logger from railrl.data_management.images import normalize_image from railrl.envs.vae_wrappers import VAEWrappedEnv from railrl.torch import pytorch_util as ptu from railrl.visualization.video import du...
# Author: <NAME> # Created: 9/4/20, 10:28 AM import logging import argparse import os import pandas as pd from typing import * import seaborn from Bio import SeqIO import matplotlib.pyplot as plt # noinspection All import pathmagic # noinspection PyUnresolvedReferences import mg_log # runs init in mg_log and conf...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json from frappe.model.document import Document from frappe import _ from frappe.utils import get_url from razorpay_integ...
#!/usr/bin/env python3 import os import sys import re import argparse # Package use pattern package_use_re = re.compile('(\w+)::([\*\w]+)') # Include use pattern include_use_re = re.compile('`include\s+["<]([\w/\.\d]+)[">]') # Module instance pattern, assuming parentheses contents removed module_instance_re = re.co...
from flask import Flask, render_template, request, url_for, redirect, session import os, atexit, shutil, json import ePUBConverter, webbrowser, random, threading from pathlib import Path app = Flask(__name__, template_folder = "templates") SESSION_TYPE = 'filesystem' ''' For session secret key ''' app.secret_key = "h...
import datetime import uuid from dataclasses import dataclass, field from typing import Optional, Generator, Dict, List from protogen.stalk_proto import models_pb2 as backend from ._enums import TimeOfDay, Patterns @dataclass class PhaseInfo: price: Optional[int] name: str date: datetime.date time_...
import numpy as np from typing import List from itertools import product import string import re #import tensorflow as tf from tokenizers import Encoding from transformers import BatchEncoding, BertTokenizerFast from transformers import TFBertModel from scripts.utils import Collection, Keyphrase, Sentence, ENTITIES fr...
import math import torch from torch.nn import functional as F def relu1(x): return F.relu6(x * 6.) / 6. def flat_reduce(tensor, reduce_type='sum', final_reduce='mean'): """Flattens the tensor and reduces it.""" def _reduce(tensor, how, *args): return getattr(torch, how)(tensor, *args) # pylin...
import os, time, datetime, pathlib from dateutil.relativedelta import relativedelta from dateutil.parser import parse import pandas as pd def writeOutTrainings(staff, conf, debug=False): outDir = "training" she_sheet_date = staff.SHE_spreadsheet_date totara_sheet_date = staff.Totara_spreadsheet_date fo...
import aiohttp import asyncio import json import util import settings logger = util.get_logger("discord") CG_BTC_CACHE_KEY = 'beatrice_btccache' CG_NANO_CACHE_KEY = 'beatrice_nanocache' CG_BAN_CACHE_KEY = 'beatrice_banocache' CGNANO_URL = 'https://api.coingecko.com/api/v3/coins/nano?localization=false&tickers=true&m...
#!/usr/bin/env python import requests, json, re from sys import argv from collections import defaultdict as dd from os.path import exists #Omim output from parse_genemap.py script. omim_in=argv[1] #Are we carrying out an update? In that case, re-download JSON files even if they exist. to_update=int(argv[2]) #User de...
from urllib2 import Request, urlopen, URLError import os, json, csv import logging #output from categories: def outputFiles(inputFileName, qid, occupation, occupationQID,title, language, p21, gender, firstSentence): lines = [] linesQS = [] output = open(inputFileName+" Outputs/Category Outputs CSV/"+occupation+occup...
""" The heart of the library. See ``README.rst`` and ``Configuration`` class for more details. """ import dataclasses import enum import os import warnings from typing import Any, Callable, Dict, NewType, Optional, Type, Union, get_type_hints # Aliased in order to avoid a conflict with the _Options.transform attribute...
import threading import traceback import signal import zmq from msgpack import packb, unpackb from json import dumps, loads import pickle p_dumps = pickle.dumps p_loads = pickle.loads # Achieve Ctrl-c interrupt recv signal.signal(signal.SIGINT, signal.SIG_DFL) class RpcObject(object): """ Referred to seri...
""" Calibrator for the DL0 -> DL1 data level transition. This module handles the calibration from the DL0 data level to DL1. This transition involves the waveform cleaning (such as filtering, smoothing, or basline subtraction) performed by a cleaner from `ctapipe.image.waveform_cleaning`, and the charge extraction tec...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Created by tz301 on 2020/05/22 """Convert kaldi model to tensorflow pb.""" import logging from argparse import ArgumentParser from os import environ from pathlib import Path from subprocess import run from tempfile import TemporaryDirectory from onnx import ModelProto f...
import pathlib import time from gym.wrappers import FlattenObservation from spectrl.envs.cp_continuousobstacle_env import CartPoleContObsEnv from spectrl.hierarchy.construction import automaton_graph_from_spec from spectrl.hierarchy.reachability import HierarchicalPolicy, ConstrainedEnv from spectrl.rl.ars import Hyp...
import boto3 from botocore.exceptions import ClientError import json import os import time from lib.account import * from lib.common import * import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.WARNING) logging.getLogger('boto3').setLevel(logging.WA...
# This script is designed to do a new spline interpolation # in order to avoid the discontinuity in the torsion plot... # # Y.T. 2020/02/17 # import os import numpy as np from numpy import linalg as LA from scipy import interpolate,integrate from math import sqrt import sys def get_alpha_c_xyz(inp_f): x=[[]]...
import objax import jax import jax.numpy as np import typing from typing import Callable, List def vc_to_dict(vc): """ Convert an objax varcolection to python dict """ all_vars = {} for key in vc.keys(): all_vars[key] = np.array(vc[key].value) return all_vars def remove_prefix_from_dict_key...
#!/usr/bin/env python """ ReceiveAndPlot example for LSL This example shows data from all found outlets in realtime. It illustrates the following use cases: - efficiently pulling data, re-using buffers - automatically discarding older samples - online postprocessing """ import numpy as np import math import pylsl imp...
import functools from flask import (Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app) import datetime from .auth import loginRequired from .database import getDatabase from .api import getData, getPartData, getGroupName postsbp = Blueprint('posts', __name_...
# Copyright 2019 The Texar Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
import urllib3 import bs4 try: from .CONST import HEADERS, KYM from .MemePage import MemePage from .PhotoPage import PhotoPage from .NewsPage import NewsPage except ImportError: from CONST import HEADERS, KYM from MemePage import MemePage from PhotoPage import PhotoPage from NewsPage imp...
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
# Copyright 2018 Iguazio # # 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, softwa...
# encoding: utf-8 import click import falcon import ldap, ldap.sasl import mimetypes import os import struct from datetime import datetime, timedelta from identidude.decorators import login_required, serialize, ldap_connect from identidude import config from .ssh import AuthorizedKeysResource from .lookup import Looku...
import os import utils import torch import logging import IPython import numpy as np import torchvision.datasets as dset import torchvision.transforms as transforms ZIP_DATASET = False INMEMORY_DATASET = False def create_imagenet_file_split(root_dir, portion, indices_only=False, valid_portion=-1, dataset=None): ...
""" fill a paradigm table according to a lemma """ import logging from copy import deepcopy from pathlib import Path from typing import Dict, List, Sequence, Set, Tuple import hfstol from paradigm import ( Cell, EmptyRow, InflectionCell, Layout, StaticCell, TitleRow, rows_to_layout, ) from ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 23 10:02:20 2020 @author: stoutjd """ import mne, glob, copy import pandas as pd import numpy as np def convert_annotations_to_dframe(annot): '''Code snippet pulled from mne python mne.annotations._annotations_to_csv()''' df = pd.DataFram...
import torch import numpy as np from torch import nn from typing import Any, Dict, List, Tuple, Union, Callable, Optional, Sequence from tianshou.data import to_torch def miniblock( inp: int, oup: int, norm_layer: Optional[Callable[[int], nn.modules.Module]], ) -> List[nn.modules.Module]: """Construc...
# ============LICENSE_START======================================================= # Copyright (c) 2021 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use ...
import pytz import requests import datetime from cloudify import manager from cloudify_rest_client import CloudifyClient from cloudify_rest_client.executions import Execution from cloudify import ctx TIMESTAMP_FORMAT = '%Y%m%d%H%M' LAST_SCLAING_TIMESTAMP_RP = 'last_scaling_timestamp' LAST_SCLAING_EXECUTION_ID = 'last...
import shutil import os import pickle from collections import defaultdict import torch from torch.utils.tensorboard import SummaryWriter from sequential_inference.abc.experiment import AbstractExperiment from sequential_inference.abc.util import Logger def mean_dict(lod): mean_d = {} for k in lod[0].keys(): ...
import gc import anndata2ri import numpy as np import rpy2.robjects as ro from anndata._core.sparse_dataset import SparseDataset from app import logger from controller.cellar.utils.exceptions import InvalidArgument from pydiffmap import diffusion_map as dm from rpy2.robjects import numpy2ri, r from rpy2.robjects.packa...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/...
from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rlib.rfile import c_setvbuf, _IONBF from pypy.module.cpyext.api import ( cpython_api, CANNOT_FAIL, CONST_STRING, FILEP, build_type_checkers, c_fdopen) from pypy.module.cpyext.pyobject import PyObject from pypy.module.cpyext.object import Py_PRINT_RAW...
''' this Worker takes care of return-data being returned by a minion. it takes care of dumping the 'return'-field into the database after its json-encoded and base64 converted. ''' # import and setup logger first, so we can catch # missing libraries on imports import logging log = logging.getLogger(__name__) try: ...
#!/usr/bin/env python # Copyright 2018 Palo Alto Networks, 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...
# coding: UTF-8 """ Created on Wed May 8 13:00:18 2019 @author: Administrator """ from flask import Flask, render_template, request from flask import jsonify from WhiteList import cityWhiteList,majorWhiteList import pandas as pd app = Flask(__name__) app.config['SECRET_KEY'] = "dfdfdffdad" loc_di...
import numpy as np def factorize(X1, X2, kc, kd, alpha=5, beta=1, lr=0.01, outer_loops=25, inner_loops=300, randomize_cols=False, min_change=0.001, silent=True): m, n1 = X1.shape n2 = X2.shape[1] k = kc + kd # Initialize W and H W1 = np.random.uniform(size=(m, k)) W2 = np.random.uniform(size=(...
"""Contains helper functions for loading the database. """ import pandas as pd import os import string import xlrd #import changelog #import allEntries __author__ = "<NAME>" __credits__ = ["<NAME>"] __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" # Grab the excel file in the database, ski...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import sys import optparse from .logger import logger from glue import __version__ def parse(argv): """ Parse argument list, check validity :param argv: Arguments passed to program *Returns* A tuple of options,...
# Copyright 2013 IBM Corp # # 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...
import dataclasses import threading from collections import defaultdict, deque from io import BytesIO from typing import Dict from tarpn.log import LoggingMixin from tarpn.network import QoS from tarpn.network.mesh import MeshAddress from tarpn.network.mesh.header import NetworkHeader, ReliableHeader, ReliableFlags, P...
import json import os import tempfile import zipfile from collections.abc import Sequence from datetime import datetime as dt from datetime import time from enum import Enum from pathlib import Path from typing import List, Tuple, Any from warnings import warn import alpyne from alpyne.data.model_data import ModelData...
#! -*- coding:utf-8 -*- import keras.backend as K from keras_bert import Tokenizer import numpy as np import codecs from tqdm import tqdm import json import unicodedata BERT_MAX_LEN = 512 class HBTokenizer(Tokenizer): def _tokenize(self, text): if not self._cased: text = unicodedata.normalize(...
from ast import NodeVisitor def transform(source_code): from ast import parse visitor = ModuleVisitor() visitor.visit(parse(source_code)) return visitor.tests class ModuleVisitor(NodeVisitor): def __init__(self): self.tests = [] def visit_FunctionDef(self, node): from ir im...
from __future__ import print_function import uuid import os from apiclient import discovery from httplib2 import Http from oauth2client import file from pathlib import Path from oauth2client import client if (input("Have you verified drive permissions on your google account? [y/n] ") == "y" and input("Have yo...
import os import re import subprocess from typing import List import typer app = typer.Typer() def show_err(msg: str) -> None: typer.secho(msg, err=True, fg=typer.colors.RED) def show_warn(msg: str) -> None: typer.secho(msg, err=True, fg=typer.colors.YELLOW) def show_log(msg: str) -> None: typer.sec...
import main import sys import subprocess import os import json import numpy as np def get_IOU(boxA, boxB): # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA[0], boxB[0]) yA = max(boxA[1], boxB[1]) xB = min(boxA[2], boxB[2]) yB = min(boxA[3], boxB[3]) # compute th...
import pytest from numpy.testing import assert_equal from astropy import units as u from astropy.table import Table from astropy.time import Time from ..binned import BinnedTimeSeries INPUT_TIME = Time(['2016-03-22T12:30:31', '2015-01-21T12:30:32', '2016-03-22T12:30:40']) PLAIN...
import numpy as np import sys import os from scipy.interpolate import InterpolatedUnivariateSpline as Spline from predict_cl import AngularPowerSpectra from cobaya.theory import Theory from cobaya.likelihood import Likelihood class ClLikelihood(Likelihood): # From yaml file. clsfn: str covfn:...
""" Copyright (C) 2019 Authors of gHHC This file is part of "hyperbolic_hierarchical_clustering" http://github.com/nmonath/hyperbolic_hierarchical_clustering 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 Lice...
# SI 506 Problem Set 04 # Part 1 menu = [ ["name", "categories", "price (HKD)"], ["short ribs with xo source", "steamed", 28], ["pan-fried turnip cake", "Pan-fried/Baked", 22], ["Malay sponge cake", "sweet", 17], ["baked egg tart", "sweet", 18], ["custard bun", "steamed", 21], ["barbecued p...
import math from PyQt4.QtCore import QRectF, QPointF from PyQt4.QtGui import QGraphicsPathItem, QPen, QBrush, QColor, QPainterPath, QGraphicsItem from port_item import PortItem def anchors(count, startAngle, arcLen, radiusOut, radiusIn): angleIncr = arcLen / float(count + 1) radius = radiusIn + (radiusOut -...
from __future__ import print_function import base64 import getpass import os from pprint import pprint from six.moves.urllib.parse import urlparse import builtins import requests import websocket from .config import PdtoolsConfig PDSERVER_URL = os.environ.get('PDSERVER_URL', 'https://paradrop.org') LOCAL_DEFAULT_...
from fog_env import Offload from RL_brain import DeepQNetwork import numpy as np import random # import matplotlib.pyplot as plt np.set_printoptions(threshold=np.inf) def random_pick(some_list, probabilities): x = random.uniform(0, 1) cumulative_probability = 0.0 for item, item_probability in z...
""" Author: <NAME> Institute: Stony Brook University This files contain the Tools of DMTRL. """ import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from scipy.linalg.interpolative import svd """This part is refered from the official code in https://github.com/wOOL/DMTRL/b...
import torch import torch.nn as nn from pytorch3d.loss import chamfer_distance from torch.nn.utils.rnn import pad_sequence import torch.nn.functional as F class SILogLoss(nn.Module): # Main loss function used in AdaBins paper def __init__(self): super(SILogLoss, self).__init__() self.name = 'SILo...
import sys import torch import unittest from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from torch.nn import CrossEntropyLoss from torch.optim import SGD from torch.utils.data import TensorDataset from avalanche.benchmarks import nc_scenario from avalanche.loggin...
# -*- coding: utf-8 -*- import logging import os from django.conf import settings from django.db import models from django.db.models.fields import IntegerField from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager from apps.gallery import settings as gallery_settings from...
""" Utility functions. """ import numpy as np import os import random import tensorflow as tf from tensorflow.python.platform import flags FLAGS = flags.FLAGS ## Image helper def path_process(image_path): depth_path = image_path.replace('_scene.jpg', '_depth1D.jpg') box_path = image_path.replace('.jpg', '.dat...
import torch import torch.nn as nn from torch.autograd import Variable def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) ...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import logging from typing import Any, Dict, List import mock import pytest from datadog_checks.base import ConfigurationError from datadog_checks.base.stubs.aggregator import AggregatorStub from datadog...
import xlsxwriter import pandas as pd #Global Variables course = [] cg = 0 courselist = [] list_of_attempted_courses = [] list_of_completed_courses = [] list_of_retake_courses = [] weighted_cg = 0 creds_attempted = 0 creds_completed = 0 def add(course_name, course_cgpa, course_credits): course.append([course_nam...
from typing import List from fractions import Fraction from abc import ABC, abstractmethod import spacy import string import random import requests import pandas as pd import diskcache from somajo import SoMaJo def has_space(text: str) -> bool: return any(x.isspace() for x in text) class Tokenizer(ABC): def...
import json import os from os.path import join from django.forms import model_to_dict from django.http import HttpResponse, JsonResponse from django.template.response import TemplateResponse from django.utils import timezone from django.views.decorators.csrf import ensure_csrf_cookie from main.internals.con...
# Copyright 2018 The GraphNets Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
from __future__ import division import numpy as np from menpo.shape import PointCloud, TriMesh from menpo.transform .affine import Translation, SimilarityTransform from menpo.image import MaskedImage def build_reference_frame(landmarks, boundary=3, group='source', trilist=None): r""" ...
# source-to-source compiler from collections import OrderedDict from spi import ( Lexer, Parser, NodeVisitor, BuiltinTypeSymbol, VarSymbol, ProcedureSymbol ) class ScopedSymbolTable(object): def __init__(self, scope_name, scope_level, enclosing_scope=None): self._symbols = Ordere...
from abc import ABC from typing import List, Text from flask import current_app, redirect, render_template, request, session, url_for from flask_babel import _ from notifications_python_client.errors import HTTPError from app import billing_api_client, service_api_client from app.main import main from app.main.forms ...
# Copyright 2016, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any later ...
import re from typing import Any, List, Optional from algoliasearch_django.decorators import disable_auto_indexing from allauth.account.models import EmailAddress from import_export import fields from import_export.fields import Field from import_export.resources import ModelResource from import_export.widgets import ...
import pytest from rest_api.controller.request import Question from rest_api.controller.response import Answer, AnswersToIndividualQuestion def test_query_dsl_with_without_valid_query_field(): query = { "query": { "bool": { "must": [ {"match": {"title": "Se...
import math import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as mpathes import colour #Luminance of background Y_value = 0.14 Y_sRGB = colour.models.eotf_inverse_sRGB(Y_value) #Inspired by the image on https://en.wikipedia.org/wiki/Helmholtz%E2%80%93Kohlrausch_effect # **...
""" This is my toolbox module. I'll put procedures in here that I might want to use again in the future. If I put something in here, I will also print that procedure out and include it with my source code when I turn in the first program that I use it on. After that, I won't have to print it out and turn it in again. ...
from __future__ import print_function import argparse, os, sys import imp import logging from os.path import dirname import werkzeug.serving from bokeh import __version__ from bokeh.server.utils.reload import robust_reloader from bokeh.server.app import bokeh_app from bokeh.settings import settings DEFAULT_BACKEND ...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-Core project. # # 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 ...
import os import pdb import time import sys from optparse import OptionParser import numpy as np import keras import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import * from data.twitter import data from data.twitter import data_retrieval from seq2seq_word import build_seq2seq_word, load_data,...
import matplotlib.pyplot as plt import numpy as np import os import math def learning_rate(init, epoch): optim_factor = 0 if(epoch > 160): optim_factor = 3 elif(epoch > 120): optim_factor = 2 elif(epoch > 60): optim_factor = 1 return init*math.pow(0.2, optim_factor) def a...
import json from json import JSONDecodeError from typing import List, Dict, Tuple import requests from config import Config from flask_app.match_score import MatchPlayer, ScoreData from flask_app.player import Player from flask_app.schedule import schedule, Match from flask_app.team import UserTeam from flask_app.use...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
"""Statcast Pitcher Spin These calculations are based on the work by Prof. <NAME> of the University of Illinois. Article: http://baseball.physics.illinois.edu/trackman/SpinAxis.pdf Excel Workbook: http://baseball.physics.illinois.edu/trackman/MovementSpinEfficiencyTemplate-v2.xlsx """ from pybaseball import statcast...
# Copyright 2020 D-Wave Systems 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...
import functools import itertools import os.path import pathlib from typing import Sequence import create_corpus THIS_DIRECTORY = pathlib.Path(os.path.abspath(__file__)).parent FRY_WORDS_PATH = THIS_DIRECTORY / "fry.txt" DOLCH_WORDS_PATH = THIS_DIRECTORY / "dolch.txt" DOLCH_NOUNS_PATH = THIS_DIRECTORY / "dolch-nouns...
############################################################################### # Copyright (c) 2019, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by the Merlin dev team, listed in the CONTRIBUTORS file. # <<EMAIL>> # # LLNL-CODE-797170 # All rights reser...
#!/usr/bin/python3 import sys import json import numbers # Using plotly.express import plotly.graph_objects as go from datetime import datetime # sys.argv[1] = data (all database data) try: # get data from sys.argv[1] and convert them into python dictionary userData = json.loads(sys.argv[1]) except IndexError...
import dataclasses from dataclasses import dataclass class Element: # Cast types def __post_init__(self): """ Cast all fields """ for field in dataclasses.fields(self): value = getattr(self, field.name) if not isinstance(value, field.type): ...
import json import os import sys import requests # https://pyfpdf.readthedocs.io from fpdf import FPDF from grid import parse_batch, generate_grid_and_cell_data PDF_ROOT = f"{os.path.expanduser('~')}/pdfs" # COLORS BLACK = (0, 0, 0) DARK = (64, 64, 64) WHITE = (255, 255, 255) LIGHT_GREY = (151, 151, 151) GRAY = (240, ...
import json import copy from web3 import Web3, KeepAliveRPCProvider from sonar.ipfs import IPFS class Gradient(): def __init__(self, owner, grad_values, gradient_id, new_model_error=None, new_weights=None): self.owner = owner self.grad_values = grad_values self.id = gradi...
""" The data models for polls, choices and votes """ import datetime from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.db.models import permalink from django.http import Http404 from dj...
import paho.mqtt.client as mqtt from serial import Serial import threading import config import json import signal import sys import socket from mavlink import * # SERVER_IP = "127.0.0.1" # SERVER_IP = "192.168.10.12" # HOSTNAME = "rtls.local" HOSTNAME = "localhost" class StoppableThread(threading.Thread): """Th...
''' Copyright (c) 2021 <NAME>, <NAME>, Technical University of Denmark ''' # Import modules import os import pandas as pd import freesasa as fs from Bio.PDB import PDBParser import pkg_resources import json from natsort import natsort_keygen # Path to resource files naccess_config = pkg_resources.resource_filename(__...
import sys import os import argparse import logging import shutil import platform import pkg_resources import stat import ntpath from ament_index_python import get_package_prefix, get_package_share_directory from ament_index_python.packages import PackageNotFoundError class UnityROS2LibCopier: def __init__(self,...
# from CTL.causal_tree.util import * try: from CTL.causal_tree.util_c import * except: from CTL.causal_tree.util import * from CTL.causal_tree.ct import * import numpy as np from scipy.stats import ttest_ind_from_stats class SigNode(CTNode): def __init__(self, p_val=1.0, effect=0.0, node_depth=0, control...
''' Based on Parsedom for XBMC plugins Copyright (C) 2010-2011 <NAME> And <NAME> 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, or (at your option)...
import asyncio import logging import random import ssl import time from typing import Any, Optional, Tuple import msgpack from rap.common.asyncio_helper import done_future, safe_del_future from rap.common.state import State from rap.common.types import READER_TYPE, UNPACKER_TYPE, WRITER_TYPE from rap.common.utils imp...
from pandas import read_csv from multiprocessing import Pool, cpu_count from itertools import repeat import tqdm import os import datetime # Initializing core folders. currentWorkingDirectory = os.getcwd() folders = { 'historical': os.path.join(currentWorkingDirectory, 'historical_data'), 'indicat...