text stringlengths 3.07k 12.6k |
|---|
import numpy as np
import pandas as pd
import json
import requests
from shapely.geometry import LineString
from sklearn.cluster import KMeans
import time
import os
from geocoding.config import Config
def query_api(query, fpath):
"""
Queries Overpass API for *query*.
Args:
query (str): The query ... |
import os
import meshio
import numpy as np
import pandas as pd
import ezdxf
catalogue_columns = ["t0", "m0", "mw", "x", "y", "z", "area", "dt"]
def read_binary(file: str, format: str, endian: str = "little"):
"""
Reads integer values from binary files that are output of RSQSim
:param file: file to read... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
from typing import Generator, Tuple
from volatility.framework import constants
from volatility.framework import objects, interfaces... |
import io
from http.client import HTTPException
from urllib.error import HTTPError
from Bio import Entrez, SeqIO
from .. import configuration
from ..request import Http400, RequestErrors, request
Entrez.email = configuration.settings["EMAIL"]
Entrez.api_key = configuration.settings.get("NCBI_API_KEY")
class Refere... |
import copy
import os
import random
import numpy as np
import torch
import torch.nn as nn
from torch import fx
from torchvision.models import MNASNet, MobileNetV3, ShuffleNetV2
from torchvision.models.densenet import _DenseLayer
def matches_module_pattern(pattern, node, modules):
if len(node.args) == 0:
... |
from vispy import scene, color as coloring
from SimulationState import GridDimensions, BoundaryConditionType, BoundaryConditionSetter
import numpy as np
class QuantumSimulationLines():
def __init__(self, gridExtents : GridDimensions):
self.Real = EditableSimulationLine.InitialLine(1, "blue", gridExtents)
... |
"""
monobit.struct - property structures
(c) 2019--2021 <NAME>
licence: https://opensource.org/licenses/MIT
"""
from types import SimpleNamespace
from functools import partial
import ctypes
import struct
from ctypes import sizeof
def reverse_dict(orig_dict):
"""Reverse a dict."""
return {_v: _k for _k, _v i... |
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip
import collections
import numpy as np
import json
EDGE_INDEX = 0
UNKNOWN_INDEX = 1
#######################... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2017, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import sys
from typing import Tuple, Callable, Any
from protoactor.persistence.messages import Event, Snapshot, RecoverSnapshot, RecoverEvent, PersistedEvent, \
PersistedSnapshot
from protoactor.persistence.providers.abstract_provider import AbstractSnapshotStore, AbstractEventStore
from protoactor.persistence.sna... |
#!/usr/bin/env python3
import os
from os import path
import subprocess
def run_command(args, dry_run=False, verbose=False):
if dry_run or verbose:
print(" ".join(args))
if not dry_run:
subprocess.run(args)
def main():
import argparse
parser = argparse.ArgumentParser(
descri... |
"""
This module implements the G0W0 approximation on top of `pyscf.tdscf.rhf_slow` TDHF implementation. Unlike `gw.py`, all
integrals are stored in memory. Several variants of GW are available:
* `pyscf.gw_slow`: the molecular implementation;
* `pyscf.pbc.gw.gw_slow`: single-kpoint PBC (periodic boundary condition) ... |
#!/usr/bin/env python
"""
Usage:
error_analysis.py [options] MODEL_PATH (--standard-dataset | --method2code-dataset) DATA_PATH OUT_FILE
Options:
-h --help Show this screen.
--max-num-epochs EPOCHS The maximum number of epochs to run [default: 300]
--max-num-files INT ... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import View
from . import models
from . import forms
# Create your views here.
def empty_redirect(request):
return HttpResponseRedirect(reverse_lazy('Apps.User:index')... |
"""
@file
@brief Functions to show shortened options in :epkg:`asv` benchmarks.
"""
def expand_onnx_options(model, optim):
"""
Expands shortened options. Long names hide some part
of graphs in :epkg:`asv` benchmark. This trick converts
a string into real conversions options.
@param model ... |
import torch.nn as nn
import torch
from collections import OrderedDict
from DNCNN.networks import basicblock as B
class UNet(nn.Module):
def __init__(self, in_nc=6, out_nc=3, nc=[64, 128, 256, 512], nb=2, act_mode='R', downsample_mode='strideconv', upsample_mode='convtranspose'):
super(UNet, self).__init_... |
import ast
from ward.tests.utilities import testable_test
from ward import test, fixture
from ward.rewrite import (
rewrite_assertions_in_tests,
RewriteAssert,
get_assertion_msg,
make_call_node,
is_binary_comparison,
is_comparison_type,
)
from ward.testing import Test, each
@testable_test
def... |
# -*- coding: utf-8 -*-
"""
Vistara Runner
Runner to interact with the Vistara (http://www.vistarait.com/) REST API
:codeauthor: <NAME> <<EMAIL>>
To use this runner, the Vistara client_id and Vistara oauth2 client_key
and client_secret must be set in the master config.
For example ``/etc/salt/master.d/_vistara.conf... |
import cv2
import glob, os
import numpy as np
import imutils
import pytesseract
import re
import time
import CSVHelper
import multiprocessing
import concurrent.futures as cf
DEBUG = False
def showIMG(mat, name, delay=0):
if not DEBUG:
return
cv2.namedWindow(name, cv2.WINDOW_KEEPRATIO)
cv2.imshow(n... |
#!/usr/bin/env python3
import os
import logging
import uuid
import datetime
from jsonobject import PropertySet, Property, register_schema
from images7.system import current_system
from images7.config import resolve_path
from images7.job import JobHandler, Job, register_job_handler
from images7.job.transcode import g... |
# -*- coding: utf-8 -*-
#
# Project: silx (originally pyFAI)
# https://github.com/silx-kit/silx
#
# Copyright (C) 2012-2017 European Synchrotron Radiation Facility, Grenoble, France
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docume... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyri... |
"""
DIRBS REST-ful IMEI API Schema module.
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
- Re... |
import numpy as np
import torch
import torch.nn.functional as F
import sys
import pandas as pd
from progressbar import ProgressBar, AnimatedMarker, Percentage
import math
from tqdm import trange
def Video_Cmc(features, ids, cams, query_idx,rank_size):
"""
features: numpy array of shape (n, d)
label`s: num... |
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# 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 lim... |
import torch
from torch.nn import functional as F
from torch.autograd import Variable
import torch.nn as nn
import math
import numpy as np
from ..config import eps
class ConvBlock4(torch.nn.Module):
def __init__(self, inpt_kernel, output_kernel, kernel_size=4, stride=1, padding=0):
super().__init__()
... |
# Importing all from tkinter
from tkinter import *
from PIL import Image, ImageTk
from random import randint
# Creating Main Window or Container
# root is the name of the main window object
root = Tk()
# Changing the title of the application
root.title("Rock Paper Scissor")
# Background color for the app... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, os.path
import requests
import re
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
from pdfconverter import to_pdf
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-pdf","--pdf_directory", dest="DIR_DOWNLOADED", help = "Path to t... |
"""Define losses."""
import tensorflow as tf
def _smooth_one_hot_labels(logits, labels, label_smoothing):
label_smoothing = tf.constant(label_smoothing, dtype=logits.dtype)
num_classes = tf.shape(logits)[-1]
return tf.one_hot(
tf.cast(labels, tf.int32),
num_classes,
on_value=1.0 - label_smoot... |
# -*- coding: utf-8 -*-
"""Tests for data structures in PyBEL."""
import unittest
from six import StringIO, string_types
from pybel import BELGraph
from pybel.constants import CITATION_REFERENCE, CITATION_TYPE, CITATION_TYPE_PUBMED
from pybel.dsl import hgvs, protein
from pybel.testing.utils import n
class TestGr... |
import os
import torch
import csv
import random
import numpy
import json
from math import pi
from torchvision import transforms
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# Image Processing
def shuffle(ts, dim=0, inv=False):
if inv:
idx = torch.arange(ts.size(dim) - 1, -1, step... |
#! python
import csv
import glob
import random
import math
import operator
from functools import reduce
import os
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
from os import system, name
import numpy as np
def clear():
'''
define console clear function
'''
# for windows
... |
import numpy as np
import os
import xml.etree.ElementTree as ET
from typing import List, Tuple, Union
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import BoxMode
from detectron2.config import get_cfg
from detectron2 import model_zo... |
#!/usr/bin/env python
"""
Module containing the tools for plotting of results
"""
import os
from bilby.core.utils import check_directory_exists_and_if_not_mkdir
from bilby.gw.result import CBCResult
from bilby.gw.source import (
binary_black_hole_roq,
binary_neutron_star_roq,
lal_binary_black_hole,
lal... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme 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 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
DOCUMENTATION = '''
---
module: installation_template
short_description: Manage installation templates for dedicated servers
descripti... |
import pickle
import os
import sys
import codecs
import re
from tqdm import tqdm
def read_corpus(arg):
if os.path.isdir(arg):
# If a directory, grab lines from every file in the directory
lines = []
for filename in [os.path.join(arg, f) for f in os.listdir(arg)]:
sys.stderr.writ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 26 11:14:48 2021
@author: grat05
"""
import tkinter as tk
from tkinter import messagebox, ttk
from copy import deepcopy
class HSVEntryWidget(tk.Frame):
def __init__(self, parent, label, data=None):
tk.Frame.__init__(self, parent)
... |
#!/usr/bin/env python3
# This file is part of the MicroPython project, http://micropython.org/
# The MIT License (MIT)
# Copyright (c) 2019 <NAME>
import os
import subprocess
import sys
import argparse
sys.path.append('../tools')
import pyboard
# Paths for host executables
CPYTHON3 = os.getenv('MICROPY_CPYTHON3', '... |
import torch
from torch import nn
from onnx import numpy_helper
from onnx2pytorch.operations import BatchNormUnsafe, InstanceNormUnsafe
from onnx2pytorch.convert.attribute import extract_attributes, extract_attr_values
import math
import torch.nn.functional as F
def extract_params(params):
"""Extract weights and... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Modified by BaseDetection, Inc. and its affiliates.
import logging
import time
import weakref
from typing import Dict
import numpy as np
import torch
from cvpods.utils import comm
from cvpods.utils.dump.events import EventStorage, get_event_storage
from cvpods.ut... |
from collections import Counter
from tqdm import tqdm
from sklearn.metrics import precision_score, recall_score, accuracy_score, f1_score, auc, average_precision_score, confusion_matrix, roc_auc_score
from tqdm import tqdm
import pandas as pd
import numpy as np
import requests
import matplotlib.pyplot as plt
import sea... |
# coding=utf-8
#
# Copyright © 2015 VMware, Inc. All Rights Reserved.
#
# 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, co... |
import argparse
import sys
from os.path import abspath
from json import dumps
from charset_normalizer import from_fp
from charset_normalizer.models import CliDetectionResult
from charset_normalizer.version import __version__
from platform import python_version
def query_yes_no(question, default="yes"):
"""Ask a... |
import Functions.AdminFunctions as AF
from Functions.ScrapeFunctions import *
import pandas as pd
import os, sys
import time
import random
def crawl_issues(journal, from_volume, from_issue, to_volume, to_issue, continuous_issue_inc=False):
'''
:param journal:
:param from_volume:
:param from_issue:
... |
import math
from pygame import Rect
from pygine.draw import draw_rectangle
from pygine.utilities import CameraType, Color
class Quadtree:
def __init__(self, boundary, capacity):
self.boundary = boundary
self.capacity = capacity
self.divided = False
self.insertion_index = 0
... |
"""Collection of admin utility functions"""
import logging
import os
import subprocess
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
from nvp.nvp_project import NVPProject
logger = logging.getLogger(__name__)
def register_component(ctx: NVPContext):
"""Register t... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import sys
import datetime
import pandas as pd
import tabula
import re
from janome.tokenizer import Tokenizer
import numpy as np
def getLastMeetingNo():
df = pd.read_csv('data/monitoring_comments.csv')
if len(df.index) > 0:
return int(df.... |
import json
# This class defines a Metric to support your Expectation
# For most Expectations, the main business logic for calculation will live here.
# To learn about the relationship between Metrics and Expectations, please visit
# https://docs.greatexpectations.io/en/latest/reference/core_concepts.html#expectations... |
#
# 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... |
# -*- coding: utf-8 -*-
"""
This module contains routines related to output of data to netCDF file.
Uses CF conventions to ensure standardized output
"""
from collections import OrderedDict
import numpy as np
import netCDF4 as nc
import yaml
class NCOutVar(object):
"""
This class contains the relavent inform... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
#!/usr/bin/python
# fEVR (Frigate Event Video Recorder) Events Menu
#
# Copyright (C) 2021-2022 The Bearded Tek (http://www.beardedtek.com) <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 So... |
'''
A simple tool to generate sample of output of a GAN,
subject to filtering, sorting, or intervention.
'''
import torch, numpy, os, argparse, numbers, sys, shutil
from PIL import Image
from torch.utils.data import TensorDataset
from netdissect.zdataset import standard_z_sample
from netdissect.progress import default... |
# Copyright 2021 Modelyst LLC
#
# 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... |
import socket
import base64
import pickle
import threading
import multiprocessing
import hashlib
class MAIN():
def __init__(self,client_name : str = None, secure = False, DSP_enable : bool = False, file : str = None, debug : bool = False, rememberServer = True, MPCL : bool = False, MTCL : bool = True):
s... |
"""Contains an abstract class that makes it easier to implement load word
vectors from text files.
"""
__author__ = '<NAME>'
from typing import List, Dict
from dataclasses import dataclass, field, InitVar
from abc import abstractmethod, ABCMeta
import logging
from pathlib import Path
import pickle
import numpy as np
... |
import pytest
from rdflib import RDF, Dataset, Graph, Literal, Namespace, URIRef
from rdflib.namespace import DCTERMS, SKOS
"""
Testing scenarios:
1. no base set
2. base set at graph creation
3. base set at serialization
4. base set at both graph creation & serialization, serialization overrides
5... |
""" Color data builder objects"""
from explorer import get_spends
from toposort import toposorted
from colorvalue import SimpleColorValue
class ColorDataBuilder(object):
pass
class ColorDataBuilderManager(object):
"""Manages multiple color data builders, one per color"""
def __init__(self, colormap, bl... |
"""
Molotov-based executor for Taurus.
Copyright 2017 BlazeMeter 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 l... |
# -*- coding: utf-8 -*-
#
# Copyright 2019-2020 Data61, CSIRO
#
# 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 uuid
from typing import Dict
from marshmallow import (
fields,
pre_load,
post_load,
pre_dump,
post_dump,
ValidationError,
)
from ..models.base import (
BaseModel,
BaseModelSchema,
resolve_class,
resolve_meta_property,
)
from ..models.field_signature import FieldSignatur... |
from typing import Union, Tuple, Optional
from django.contrib.auth.decorators import login_required
from django.contrib.postgres.search import SearchQuery, SearchVector
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q, QuerySet
from django.http import Http404, Htt... |
#!/usr/bin/env python
"""
Run an environment with the chosen policy.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import ast
import os
import random
import socket
import uuid
from builtins import input
import numpy as np
import h5py... |
import os
import sys
import yaml
import json
import pprint
import pathlib
import logging
import inspect
import argparse
import itertools
import importlib
from genie.metaparser import MetaParser
IGNORE_DIR = ['.git', '__pycache__', 'template', 'tests']
IGNORE_FILE = ['__init__.py', 'base.py', 'utils.py']
AVAILABLE_FUN... |
import requests, datetime
import json, os, os.path
from .gqlclient import GqlClient
from .constants import url, anime, manga
from collections import namedtuple
from .wrappers.media import Media, MediaTitle, AiringSchedule, MediaTrailer, MediaImage, MediaTag, MediaExternalLink, MediaStreamingEpisode
from .wrappers.cha... |
"""
Handlers required by the core chain operations
"""
import json
from time import sleep, time
from tornado import escape
from yadacoin.http.base import BaseHandler
from yadacoin.core.common import ts_to_utc
from yadacoin.core.chain import CHAIN
from yadacoin.core.transaction import Transaction
class GetLatestBloc... |
# Copyright 2013-2014 Massachusetts Open Cloud Contributors
#
# 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 la... |
"""Utility functions to translate dataclass fields into valid command line arguments.
Use extract_args_from_dataclass(MyDataclass) to return a List[ArgumentField].
"""
from dataclasses import dataclass, MISSING
from enum import Enum
from typing import Any, List, Type, Optional, Tuple, Union, TypeVar
SUPPORTED_ENUM_T... |
import importlib
from . import config
import atexit
import os
HEAP_DEFAULT = 0
HEAP_UPLOAD = 1
HEAP_READBACK = 2
SHADER_BINARY_TYPE_DXIL = 0
SHADER_BINARY_TYPE_SPIRV = 1
SHADER_BINARY_TYPE_DXBC = 2
SHADER_BINARY_TYPE_MSL = 3
SHADER_BINARY_TYPE_GLSL = 4
class UnknownBackend(Exception):
pass
class BufferExcepti... |
import os
import unittest
import subprocess
from fuc.api.common import FUC_PATH
from fuc import pyvcf, pybed, pyfq, pygff
vcf_file1 = f'{FUC_PATH}/data/vcf/1.vcf'
vcf_file2 = f'{FUC_PATH}/data/vcf/2.vcf'
vcf_file3 = f'{FUC_PATH}/data/vcf/3.vcf'
bed_file1 = f'{FUC_PATH}/data/bed/1.bed'
bed_file2 = f'{FUC_PATH}/data/be... |
import requests ## libreria para hacer el request a los navegadores
from bs4 import BeautifulSoup ## libreria utilizada para parsear el html
from flask import Flask, jsonify ## librerias de flask a utilizar
import os ## libreria para el manejo de files.
import sqlite3 ##
app = Flask(__name__)
DATABASE = '../test/d... |
# -*- coding: utf-8 -*-
#
# This file is part of python-statsd-client released under the Apache
# License, Version 2.0. See the NOTICE for more information.
import random
from functools import wraps
from socket import socket, AF_INET, SOCK_DGRAM
import time
import logging
__version__ = '1.0.7'
STATSD_HOST = 'localh... |
# -*- coding: utf-8 -*-
import re
from types import SimpleNamespace
from blessed import Terminal
term = Terminal()
def repo_output_handler(repo, tabs=1, indent='\t'):
results = []
repo_condition = 'green'
for i in repo.modified:
results.append(term.yellow(f'{tabs*indent}modified: {i.path}'))
... |
# Lint as: python2, python3
# Copyright 2018 The Bazel 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
#
# Unle... |
import discord
from discord.ext import commands
import secrets
import random
import re
class Twitch(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.user_regex = re.compile(f'^\w+$')
self.badges = {
"partner": "<:verified:836850404783292435>",
"staff": ... |
# -*- coding: utf-8 -*-
""" backend.py
Using Google Distant Matrix API to obtain the distance between cities. The
distance information obtained is used to build the distance matrix. The
shortest hamiltonian path is computed using Bellman-Held-Karp algorithm.
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__date__ ... |
import os
from LAUG.aug.Word_Perturbation.multiwoz.multiwoz_eda import MultiwozEDA
from LAUG.aug.Word_Perturbation.multiwoz.db.slot_value_replace import MultiSourceDBLoader, MultiSourceDBLoaderArgs
from LAUG.aug.Word_Perturbation.multiwoz.util import load_json, dump_json
from LAUG import DATA_ROOT,REPO_ROOT
import json... |
#!/usr/bin/env python3
#
# user-statistician: Github action for generating a user stats card
#
# Copyright (c) 2021 <NAME>
# https://www.cicirello.org/
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"... |
import os
import csv
import pandas
from sklearn.svm import LinearSVC
from sklearn import linear_model, metrics
from sklearn.model_selection import train_test_split
from scipy.sparse import csr_matrix
from questionparser import QuestionParser
CORPUS_DIR = os.path.join(os.path.dirname(__file__), 'corpus')
def compare_mo... |
import torch
from torch.fft import *
import numpy as np
import scipy.io
import h5py
import torch.nn as nn
import operator
from functools import reduce
from functools import partial
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class MatReader(object):
def __init__(self, file_path, to_torc... |
import os
import sys
from datetime import datetime
from settings import CORE_DIR
# sys.path.append(str((CORE_DIR / '..').resolve()))
# print(sys.path)
from IO.db.models import Daily, Compound
__all__ = ['read_log_file', 'read_daily_line', 'read_daily_file', 'read_gcms_file']
def read_log_file(path):
"""
P... |
import copy
class Matrix:
def __init__(self, inper):
self.rows, self.columns = inper.split()
def create(self):
self.matrix = [[float(n) for n in input().split()] for _row in range(int(self.rows))]
def add(self, mtx):
if self.rows == mtx.rows and self.columns == mtx.columns:
... |
from datetime import date, time
import numpy as np
import pandas as pd
import pytest
import pytz
from snowexsql.interpretation import *
@pytest.mark.filterwarnings('ignore:Assuming')
@pytest.mark.parametrize("card,expected", [('n', 0), ('S', 180), ('S/SW', 202.5), ('West', 270)])
def test_cardinal_to_degrees(card, ... |
import random
from math import ceil
enchs = ['ATK', 'ATK%', 'DEF', 'DEF%', 'MDEF', 'MDEF%', 'INT', 'INT%', 'HP', 'HP%']
enchs_acc = ['ATK', 'ATK%', 'DEF', 'DEF%', 'MDEF', 'MDEF%', 'INT', 'INT%', 'HP', 'HP%', 'CRIT%']
testing_base_stats = {
'HP': 3760,
'ATK': 550,
'INT': 243,
'DEF': 260,
'MDEF': 17... |
import os
import datetime
import requests, json
from django.contrib.auth.models import User
from django.core.mail import send_mail
## Global var to be used any time we need to use the range or min/max # of
## Google's category scoring scale. Names changed for more global usage.
## Ex: An accessibility score isn... |
#!/usr/bin/python3
# Demonstrates Cell/Toon shading with a 1D texture
# <NAME>
# <EMAIL>
# Heavily based on Toon.cpp
# OpenGL SuperBible
# Program by <NAME>.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import time
from math import sin, cos
i... |
from django.db import models
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
from django.db.models.fields import TextField
from tinymce.models import HTMLField
from django.dispatch import receiver
from django.db.models.signals import post_save
# Create your models here.
cla... |
# coding=utf-8
import glob
import math
import os
import numpy as np
import sys
sys.path.append('.')
from absl import app
from absl import flags
from absl import logging
import scipy.io as sio
from dataset_preparation.dataset_utils import write_seqs_to_tfrecords
import cv2
flags.DEFINE_string('dir', '/home/username... |
#!/usr/bin/env python3
# Simple test for NeoPixels on Raspberry Pi
import time
import board
import neopixel
# Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18
# NeoPixels must be connected to D10, D12, D18 or D21 to work.
pixel_pin = board.D18
global_brightness=0.2
# The number of Ne... |
import os
import numpy as np
import warnings
import scipy.constants as sc
import optical_models as om
class Metal:
'''
Outline for a class describing metals.
'''
def __init__(self, model,modelparams):
if model=='DrudeSommerfeld':
if np.size(modelparams)!=2:
raise Exception('modelparams must have exa... |
import sublime
from os import path
import urllib
import json
import subprocess
import re
from .settings import get_setting
server_addr = "http://127.0.0.1:15155"
cli = 'padawan'
server_command = 'padawan-server'
class Server:
def start(self):
subprocess.Popen(
server_command,
sh... |
from sklearn.datasets import load_boston
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#from icecream import ic
import random
from functools import reduce
from collections import defaultdict
from nn import Placeholder#导入
# sns.heatmap(dataframe.corr())
# x, y ; x with 13 dimensi... |
#!/usr/bin/env python3
'''
ME 462 TERM PROJECT - 2020 Spring
Created by Engineers with Attitude:
<NAME>
<NAME>
<NAME>
This is Game Manager.
'''
import robotarena as ra
import numpy as np
import math
import sys
from os import listdir
from os.path import isfile, join
class GeneralGameMenage... |
import synapseclient
import pandas as pd
import mock
import pytest
from genie import cna
def createMockTable(dataframe):
table = mock.create_autospec(synapseclient.table.CsvFileTable)
table.asDataFrame.return_value = dataframe
return(table)
def table_query_results(*args):
return(table_query_results_... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
MAST Portal
===========
Module to query the <NAME> Archive for Space Telescopes (MAST).
"""
from __future__ import print_function, division
import warnings
import json
import time
import os
import re
#import keyring
import io
import numpy as np
f... |
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Copyright (c) 2013-2017 <NAME> <<EMAIL>>
# Copyright (c) 2013 Mime Consulting Ltd. <<EMAIL>>
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to... |
import datetime
import aiomysql.sa
import aiopg.sa
import motor.motor_asyncio as aiomotor
import pytest
import sqlalchemy as sa
import trafaret as t
# from sqlalchemy.dialects import postgresql
from sqlalchemy.schema import CreateTable, DropTable
from trafaret.contrib.object_id import MongoId
from trafaret.contrib.rf... |
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing infra build stages."""
from __future__ import print_function
import os
import shutil
from chromite.cbuildb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.