text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
""" XIO plugin for the export parameters as an XDS.INP format
See http://xds.mpimf-heidelberg.mpg.de/html_doc/xds_prepare.html
"""
__version__ = "0.4.1"
__author__ = "<NAME> (<EMAIL>)"
__date__ = "27-11-2013"
__copyright__ = "Copyright (c) 2007-2013 <NAME>"
__license__ = "New BSD, http://w... |
from __future__ import annotations # noqa: F401
import re
import warnings
import numpy as np
import pandas as pd
import xarray as xr
from .config import config
from .grid import _wrf_grid_from_dataset
def _decode_times(ds: xr.Dataset) -> xr.Dataset:
"""
Decode the time variable to datetime64.
"""
... |
# pylint: disable=no-self-use,line-too-long
from __future__ import absolute_import
from __future__ import print_function
from allennlp.common.testing import AllenNlpTestCase
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
def demo_model(archive_file , predictor_name ... |
"""
DeepLabCut Toolbox
https://github.com/AlexEMG/DeepLabCut
<NAME>, <EMAIL>
<NAME>, <EMAIL>
This script analyzes videos based on a trained network (as specified in myconfig_analysis.py)
You need tensorflow for evaluation. Run by:
CUDA_VISIBLE_DEVICES=0 python3 AnalyzeVideos.py
"""
###############################... |
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
#!/usr/bin/python
# make code as python 3 compatible as possible
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import ast
import json
import logging
import sys
from io import BytesIO
import numpy
LOGGER = logging.getLogger()
def get_nam... |
#!/usr/bin/env python
import os, io, random
import string
import numpy as np
from Bio.Seq import Seq
from Bio.Align import MultipleSeqAlignment
from Bio import AlignIO, SeqIO
from io import StringIO
import panel as pn
import panel.widgets as pnw
import pandas as pd
pn.extension()
from bokeh.plotting import figure
... |
from scrapy.selector import Selector
import requests
import pickle
import argparse
def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('url', help="pass in URL of hotel to scrape")
args = parser.parse_args()
return args
def start_scraper(url):
return collect_reviews(url)
de... |
import html
import rich.table
import rich.text
import rich.console
from preql.context import context
from .exceptions import Signal
from .pql_types import T, ITEM_NAME
from . import pql_objects as objects
from .pql_ast import pyvalue
from .types_impl import dp_type, pql_repr
from .interp_common import call_builtin_f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import random
import time
import os
import sys
import curses
from csv import reader
# from threading import Thread
# from functools import partial
import subprocess
import datetime
def logfile(msg):
if False:
# if True:
with open("log.log"... |
import os
import glob
import pickle
from functools import wraps
from concurrent import futures
import cv2
import numpy as np
from PIL import Image
import yaml
from matplotlib import pyplot as plt
import layoutparser as lp
from tqdm import tqdm
def detect_wrapper(fn):
@wraps(fn)
def wrap(parser, im, *args, **... |
import dateutil
from typing import List
import numpy as np
import pandas as pd
from macpie._config import get_option
from macpie import lltools, strtools
def add_diff_days(
df: pd.DataFrame, col_start: str, col_end: str, diff_days_col: str = None, inplace=False
):
"""Adds a column to DataFrame called ``_dif... |
#!/usr/bin/env python3
import argparse
import pytest
import datetime
import dateutil
from dateutil.parser import parse
import os
legal_days_of_week="MTWRF"
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exceptio... |
# -*- coding: UTF-8 -*-
"""
spanning_tree
=============
Script: spanning_tree.py
Author: <EMAIL>
Modified: 2018-06-13
Original: ... mst.py in my github
extensive documentation is there.
Purpose:
--------
Produce a spanning tree from a point set. I have yet to confirm
whether it constitutes ... |
from contextlib import suppress
from typing import Callable, Union, Iterable, List, Optional, Tuple
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import zfit
from zfit import ztf
from zfit.core.interfaces import ZfitPDF
from zfit.util import ztyping
from zfit.util.exception import Sh... |
'''
do not directly run this script, you should execute the unit test
by launching the "run_test.sh"
'''
import libqpsolver
import os
import time
import progressbar
import numpy as np
from random import random
from cvxopt import matrix, solvers
#show detailed unit test message
verbose = False
#unit test run time and... |
# Copyright 2016 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the 'License'): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#******************************************************************************
# Copyright (C) 2015-2016 <NAME>
# New BSD License.
#******************************************************************************
# \file
# \brief srt file to some format
#
# Examples:
#
# ... |
from rajesh.element import Button, Div, Input
from rajesh import expr
from constants import CREDITS
class Screen(Div):
def __init__(self, app, **kwargs):
super(Screen, self).__init__(**kwargs)
self.app = app
self.app.js.info_box.innerHTML = ""
@property
def js(self):
retu... |
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional, OrderedDict, Tuple
from pydantic.fields import FieldInfo
import sqlalchemy as sa
import uvicore
from uvicore.contracts import Field as FieldInterface
from uvicore.contracts import Relation as Relati... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# main.py
#
# Copyright 2020 Alvarito050506 <<EMAIL>>
#
# 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; version 2 of the License.
#
# ... |
import matplotlib.pyplot as pyplot
from SQL import querys as sql
from Diagram import hex_converting
import seaborn as sb
import numpy as np
import pandas as ps
import sqlite3
import datetime
import config
save_plots = 'plots/'
__databaseFile = config.CONFIG['database_file_name']
sb.set(style="dark", color_codes=True)
... |
import musket_core.generic_config as generic
import musket_core.datasets as datasets
import musket_core.configloader as configloader
import musket_core.utils as utils
import musket_core.context as context
import numpy as np
import keras
import musket_core.net_declaration as net
import musket_core.quasymodels as qm
impo... |
import dnd.roll
import dnd.token as _token
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import List, Tuple, Union
Token = Tuple[int, Union[None, int, float, dnd.roll.Dice]]
def isvalue(tokid: "int") -> bool:
return tokid == _token.Int or tokid == _token.Float or tokid == _token.Dice
... |
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch import nn
from torchvision import transforms
import matplotlib.pyplot as plt
import torch
import random
import torch.nn.functional as F
from torch.utils.data.sampler import SubsetRandomSampler
random_seed = 1234
torch.ma... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 23:53:36 2020
@author: <NAME>
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from numpy import trapz
#https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
os.getcwd()
#q = variable de posición, dq0 = \dot{q}(0) = valor inicial de la derivada... |
import argparse
from pypinyin import lazy_pinyin
from pychai import Schema
import re
import time
import sys
import timeit
import profile
# 定义参数
# parser = argparse.ArgumentParser(description='manual to this script')
# parser.add_argument('--words', type=str, default='')
# parser.add_argument('--org', type=str, default... |
# Based On:
# https://github.com/kuangliu/pytorch-cifar/blob/master/models/preact_resnet.py
'''Pre-activation ResNet in PyTorch.
Reference:
[1] <NAME>, <NAME>, <NAME>, <NAME>
Identity Mappings in Deep Residual Networks. arXiv:1603.05027
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ... |
from typing import Any, Callable
from plum import dispatch
from jax.experimental import loops
import numpy as np
import jax
import jax.numpy as jnp
from jax.experimental import host_callback as hcb
from ode4jax.base import init, postamble
from .problem import ODEProblem
from .integrator import ODEIntegrator
from ... |
import logging
import os
import re
import urllib.parse
from typing import Set, List, Iterable, Dict, Optional
import requests
from bauh.api.http import HttpClient
from bauh.gems.arch import AUR_INDEX_FILE, git
from bauh.gems.arch.exceptions import PackageNotFoundException
URL_INFO = 'https://aur.archlinux.org/rpc/?v... |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2014 EOX IT Services GmbH
#
# Permission is hereby granted, free o... |
import matplotlib as mpl
import uproot3 as uproot
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
import scipy
import numpy as np
import math
import pandas as pd
import seaborn as sns
import mplhep as hep
#import zfit
import inspect
import sys
... |
from itertools import chain
from typing import NamedTuple, Dict, Sequence, List, Set, Type, Union, TYPE_CHECKING, Tuple
from lightbus.exceptions import TransportNotFound, TransportsNotInstalled
from lightbus.transports.pool import TransportPool
from lightbus.utilities.importing import load_entrypoint_classes
empty = ... |
"""
Various functions for model evaluation.
"""
import numpy as np
import pandas as pd
from utils.load_data_raw import DataGenerator_raw
from utils.custom_loss import angle_diff_deg
from utils.plot import plot_history
def model_complete_eval(model, history, part_test, params, batch_size=1024,
... |
import unittest
import numpy as np
import scipy.stats
import sys
from kldmwr import bivar
from kldmwr import distributions2d
def bvnrm_pdf(x, p):
mu = [0, 0]
sgm = [[p[0], p[1]], [p[1], p[2]]]
return scipy.stats.multivariate_normal.pdf(x, mean=mu, cov=sgm)
def bvnrm_cdf(x, p):
mu = [0, 0]
sgm = [... |
import numpy as np
from scipy.signal import savgol_filter
from qube.postprocess.dataset import Axis
def create_name(name, suffix=None, prefix=None):
elements = []
if prefix:
elements.append(str(prefix))
elements.append(str(name))
if suffix:
elements.append(str(suffix))
name = '_'.j... |
#!python
import ipaddress
import socket
import time
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
# Protocol Scanner imports
from scan_mods.protocol_scanners.http_scanner import http_scanner
from scan_mods.protocol_sca... |
import os
import tqdm
import logging
import torch
import torch.nn as nn
from torch import optim
from torch.utils.data import DataLoader, TensorDataset
from transformers import BertTokenizer
from agents.utils import Statistics
from agents.optim_schedule import ScheduledOptim
from .soft_masked_bert import SoftMaskedBer... |
# ----------------------------------------------------------------------------------------------
# CoFormer Official Code
# Copyright (c) <NAME>. All Rights Reserved
# Licensed under the Apache License 2.0 [see LICENSE for details]
# -------------------------------------------------------------------------------------... |
# Rest libraries
from flask import json, request, Response
from app.apis.namespaces import api_ns_geomodels
from flask_restx import Resource
from marshmallow import ValidationError
from marshmallow_jsonschema import JSONSchema
# Additional libraries
# Importing modules
from .schemas import ModelsSchema, ModelSchemeDe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** <NAME>
**Copyright(c):** MakeHuman Team 2001-2019
**Licensing:** AG... |
import asyncio
import json
import logging
import re
import secrets
from ipaddress import ip_address, ip_network
from operator import attrgetter
from time import time
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, List, Literal, Optional, Set
from sentry_sdk import capture_event
from sentry_sdk.util... |
## interaction / scripts / create_translation_repository.py
'''
This script will pre-calculate the translation operators for a given bounding
box, max level, and frequency steps for a multi-level fast multipole algorithm.
This can take hours to days depending on the number of threads available, size
of bounding box, n... |
import httplib2
import json
import random
import requests
import string
from flask import Flask, render_template, request, redirect, url_for, \
flash, jsonify, session as login_session, make_response
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
from sqlalchemy import create_engine
fro... |
import pandas as pd
import numpy as np
import umap
import sklearn.cluster as cluster
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
import spacy
import unicodedata
import matplotlib.pyplot as plt
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
logging.getL... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 18:13:24 2021
@author: tae-jun_yoon
"""
import numpy as np
from scipy.signal import savgol_filter
from scipy.optimize import newton
from PyOECP import References
def ListReferences():
AvailableReferences = dir(References)
for EachRefer... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CFFI bindings to enable using the XMLStarlet Toolkit Command-line utilities for XML
processing from Python.
All commands are supported:
edit(*args) - Edit/Update XML document(s)
select(*args) - Select data or query XML document(s) (XPATH, etc)
tran... |
import sys
import subprocess
import commands
import os
import six
import copy
import argparse
import time
from utils.stream import stream_by_running as get_stream_m
from utils.args import ArgumentGroup, print_arguments, inv_arguments
from finetune_args import parser as finetuning_parser
from extend_pos import extend_w... |
"""
Script containing methods useful for other plots
"""
import csv
import pathlib
import shutil
import numpy as np
from matplotlib import patches
from config import FrameworkConfiguration
def get_font_family_and_size():
"""
Function to globally set and get font family and font size for plots
"""
... |
from Sql.KLineTable import KLineTable, KLine
from Sql.StockBriefTable import StockBriefTable
from Sql.KLineBuyRecdTable import KLineBuyRecd
from Sql.ProfitRecdTable import ProfitRecdTable
from datetime import datetime
from datetime import timedelta
import pandas as pd
from pandas import DataFrame
from pandas.pl... |
# Copyright: (c) 2021, <NAME>
import numpy as np
import sys
sys.path.append('../../pyCuSDR')
from lib import *
packetData = lambda: createBitSequence(10000,seed=123) # gives us a default 10000 bit length packet
zeropad = lambda sig,n: np.concatenate((np.zeros(n),sig,np.zeros(n))) # pre and post pad signal with zer... |
from .tree_utils import load_tree
from .tree import *
from anytree import NodeMixin, RenderTree, render
import pickle
""" Operator test functions
* root : currently empty root node of a tree
* _a : does nothing currently
* _b : does nothing currently
"""
def root():
return "Executing Operator roo... |
"""NodeJS tooling orchestration.
Broadly, it has a `.nodeenv` created using the nodeenv package; and ensures that the
`node_modules` directory is kept in sync with the `package.json` file of the project.
"""
import os
import shlex
import shutil
import subprocess
import sys
import textwrap
from pathlib import Path
fro... |
import re
import os.path
from abc import ABCMeta, abstractmethod
from os import makedirs
from parso import parse
from parso.python.tree import (
EndMarker, PythonErrorLeaf, PythonErrorNode, Name, Keyword, Operator)
from config.config_parser import get_main_config_parser
class Separator():
__metaclass__ = AB... |
import pytest
import bz2
import importlib.resources
import gzip
import lzma
import uuid
import zlib
from dataclasses import make_dataclass
from fondat.error import InternalServerError, NotFoundError
from fondat.file import directory_resource, file_resource
from fondat.pagination import paginate
from fondat.stream imp... |
#!/usr/bin/env python
import astropy.units as u
from typing import Union
from dataclasses import dataclass, field, is_dataclass
from cached_property import cached_property
import copy
from typing import ClassVar
from schema import Or
from tollan.utils.dataclass_schema import add_schema
from tollan.utils.log import ge... |
import gzip
import io
import logging
import os
import six
import arff
import numpy as np
import scipy.sparse
from six.moves import cPickle as pickle
import xmltodict
from .data_feature import OpenMLDataFeature
from ..exceptions import PyOpenMLError
from .._api_calls import _perform_api_call
logger = logging.getLogg... |
#!/usr/bin/env python
# Copyright 2021 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch as th
import torch.nn as nn
import torch.nn.functional as tf
from typing import Optional, Dict
from aps.libs import Register
from aps.asr.transformer.impl import RelMultiheadAttention
from ap... |
#!/usr/bin/env python
import sys
import re
import despydmdb.desdmdbi as desdmdbi
import despymisc.miscutils as miscutils
def delete_using_run_vals(dbh, tablename, reqnum, unitname, attnum, verbose=0):
if verbose >= 1:
print("%25s" % tablename, end=' ')
sql = "delete from %s where unitname='%s' and r... |
import os
import platform
import textwrap
import pytest
from conans.test.utils.tools import TestClient
@pytest.mark.skipif(platform.system() != "Darwin", reason="Only for MacOS")
@pytest.mark.tool_cmake
@pytest.mark.tool_xcodebuild
@pytest.mark.tool_xcodegen
def test_xcodedeps_components():
"""
tcp/1.0 is a... |
import jieba
import jieba.analyse
import six
import re
import operator
import io
import jieba.posseg as pseg
def is_number(s):
try:
float(s) if '.' in s else int(s)
return True
except ValueError:
return False
def load_stop_words(stop_word_file):
"""
Utility function to load s... |
import time
import numpy as np
from PIL import Image as pil_image
from keras.preprocessing.image import save_img
from keras import layers
from keras.applications import vgg16
from keras import backend as K
import matplotlib.pyplot as plt
def normalize(x):
"""utility function to normalize a tensor.
# Argument... |
import random
import xarray as xr
import numpy as np
import scipy as sp
import networkx as nx
from collections import deque
from skimage.morphology import cube
from scipy.interpolate import interp1d
from statsmodels.distributions.empirical_distribution import ECDF
from joblib import Parallel, delayed
def label_functi... |
'''
Created on 30 aug. 2019
@author: LG
'''
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
import yaml
from pathlib import Path
import pymzn
import re
import platform
from _collections import OrderedDict
import pkg_resources
import os
import json
dummy_model = '''
... |
import math
import random
def calculate_vectors(pos_queue):
if (len(pos_queue) == 1):
return (0, 0)
for num in range(len(pos_queue) - 1, 0, -1):
dx = pos_queue[num][0] - pos_queue[num - 1][0]
dy = pos_queue[num][1] - pos_queue[num - 1][1]
# pdb.set_trace()
angle = math... |
"""
Base class for GeoRSS services.
Fetches GeoRSS feed from URL to be defined by sub-class.
"""
import codecs
import logging
import re
from datetime import datetime
from typing import Optional
import requests
from georss_client.consts import ATTR_ATTRIBUTION, CUSTOM_ATTRIBUTE
from georss_client.geo_rss_distance_hel... |
import datetime
import functools
import hashlib
from json.decoder import JSONDecodeError
import os
import pprint
from flask import current_app, request, has_request_context, json
import pytz
import six
import typing
from cape_of_good_place_names.config import config
def _deserialize(data, klass):
"""Deserialize... |
"""
Examples of using scalaps to analyze a sample of Reddit posts.
Derived from a Scala tutorial for working with the same data:
https://towardsdatascience.com/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de
"""
import urllib.request
from collections import namedtuple
from scalap... |
"""
This is awesome. And needs more documentation.
To bring some light in the big number of classes in this file:
First there are:
* ``SuperForm``
* ``SuperModelForm``
They are the forms that you probably want to use in your own code. They are
direct base classes of ``django.forms.Form`` and ``django.forms.ModelFor... |
import numpy as np
import random
def heightmap_1D(iter, smoothing, seed, init):
"""Create 2^iter + 1 linear heightmap via midpoint displacement.
"""
if init == None:
random.seed(seed + "init")
heightmap = np.array([random.random(), random.random()])
else:
heightmap = init
r... |
#!/usr/bin/env python3
#-*- coding: UTF-8 -*-
import sys
import os.path
import re
import shutil
import uuid
app = os.path.basename(__file__)
localeDir = '.'
notepad2_src = '../src/Notepad2.rc'
metapath_src = '../metapath/src/metapath.rc'
def get_available_locales():
result = []
with os.scandir(localeDir) as it:
f... |
'''
Before running this program, please execute the following statements in PostgreSQL to create tables.
This program is to parse the entities of the Stack Overflow network.
--------------------------------------------------------------
create table question(
Qid int not null primary key,
Accepted_Aid int,
Owner_Id in... |
# -*- coding: utf-8 -*-
import asyncio
import collections
import functools
import json
import time
from typing import List, Optional
from threading import Thread
from vk_api import VkApi
from vk_api.bot_longpoll import VkBotEventType, VkBotLongPoll
from vk_api.execute import VkFunction
from vk_api.upload import VkUplo... |
#!/usr/bin/env python
"""Advent of Code Programming Puzzles
2019 Edition - Day 10
Puzzle Solution in Python
"""
import argparse
import cmath
import logging
import os
import sys
from typing import Iterator
log = logging.getLogger(__name__)
# Common Methods ---------------------------------------------------------... |
"""Basic rendering options. Renderers that accept text and convert to selected formats.
"""
from omgfm import _wrapper_cmark_gfm as _cmark
from omgfm.ast_tools import (
to_c_string, from_c_string, available_options, make_options,
new_parser, parser_finish, parser_feed, parser_free, free_node)
def render(te... |
import itertools
from typing import Any
from typing import Dict
from typing import Optional
from typing import Union
import dask.dataframe as dd
import holoviews as hv
import numpy as np
import pandas as pd
from bokeh.models import HoverTool
from sid.colors import get_colors
from sid.policies import compute_pseudo_eff... |
"""Assorted plotting functions.
AUTHOR: <NAME> <britta.wstnr[at]gmail.com>
"""
import numpy as np
import matplotlib.pyplot as plt
from nilearn.plotting import plot_stat_map
from nilearn.image import index_img
def plot_score_std(x_ax, scores, title=None, colors=None, legend=None):
if colors is None:
colo... |
# flasknewsreader.py
# Version: <see below>
# Author : <NAME>
from flask import Flask, Blueprint, render_template, request, redirect
from flask_login import login_required
from datetime import datetime
from operator import itemgetter
from shutil import copyfile
import json
import os
#import logging
try:
from lib.ne... |
from settings_local import (
BITCOIND_TEST_MODE,
BITCOIND_RPC_USERNAME,
BITCOIND_RPC_PASSWORD,
BITCOIND_RPC_PORT,
BITCOIND_RPC_HOST,
BITCOIND_TEST_RPC_USERNAME,
BITCOIND_TEST_RPC_PASSWORD,
BITCOIND_TEST_RPC_HOST,
BITCOIND_TEST_RPC_PORT,
ORACLE_ADDRESS,
ORGANIZATION_ADDRESS,
... |
"""
Copyright 2020 <NAME>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense... |
import numpy as np
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from AirSimClient import *
import sys
import time
import random
import msvcrt
np.set_printoptions(threshold=np.nan)
# if true, use Q-learning. Else, use SARSA
qlearning = True
readWeights = True # read in saved weights to resume ... |
"""Parser for HA BLE (DIY sensors) advertisements"""
import logging
import struct
from Cryptodome.Cipher import AES
from .helpers import (
to_mac,
to_unformatted_mac,
)
_LOGGER = logging.getLogger(__name__)
def parse_uint(data_obj, factor=1):
"""convert bytes (as unsigned integer) and factor to float"""... |
# coding=utf-8
import os
import re
from judge.tasktype import TaskType
import json
import base64
import requests
import time
from judge.results import EvaluationResult, JudgeVerdict
from file_repository.models import FileModel
from django.core.files.base import ContentFile
import logging
logger = logging.getLogger(_... |
from common import *
from data import *
DATA_DIR = '/root/share/project/kaggle/2019/chest/data'
class XrayDataset(Dataset):
def __init__(self, split, csv, folder, mode, augment=None,):
self.split = split
self.csv = csv
self.folder = folder
self.mode = mode
self.augment = ... |
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.MMCIFParser import MMCIFParser, FastMMCIFParser
from Bio.PDB.StructureBuilder import StructureBuilder
from Bio.PDB.PDBIO import PDBIO
from Bio.PDB.MMCIF2Dict import MMCIF2Dict
from Bio.PDB.mmcifio import MMCIFIO
from Bio.PDB.Polypeptide import PPBuilder
import sys
im... |
import tensorflow as tf
import numpy as np
import pandas as pd
import pickle
import sys
sys.path.append('/Users/slade/Documents/Code/machine-learning/Python/ffm/tools.py')
from tools import transfer_data, get_batch
class Args(object):
# number of latent factors
k = 6
# num of fields
f = 24
# num ... |
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
import torch.nn.functional as F
import torch.optim as optim
import pdb
from model import *
import argparse
#task = "CLearn"
task = "CLearn_Ben"
## load m... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import WebDriverException
import time
import pandas as pd
from datetime import datetime
import platform
i... |
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME> <<EMAIL>>
# Copyright (c) 2015 <NAME> <<EMAIL>>
#
# 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 withou... |
import os
import numpy
import cv2
import random
import colorsys
from Controller.nuclick.nuclick import gen_mask
nuclei_annotation_data_root = "static/data/nuclei_annotation_data/"
color = [[0, 128, 0, 0], [255, 0, 209, 128], [0, 255, 255, 128], [0, 0, 255, 128], [0, 0, 255, 128],
[255, 191, 0, 128], [0, 0, 0... |
import torch
import ipdb
from copy import deepcopy
import random
def modify_sentence(ids, min_change=2, prob=0.1, k=2):
def _random_deletion(rids):
num_deletion = max(min_change, int(prob*len(rids)))
delete_idx = random.sample(range(len(rids)), num_deletion)
n_ids = [rids[i] for i in range... |
# Copyright (c) 2021 Massachusetts Institute of Technology
# SPDX-License-Identifier: MIT
from pathlib import Path
from typing import Any, Callable, List, Mapping, Optional, Union
from hydra._internal.callbacks import Callbacks
from hydra._internal.hydra import Hydra
from hydra._internal.utils import create_config_sea... |
from inspect import getfullargspec
from typing import Union, List, Optional
import operator
from collections import namedtuple
Patch = namedtuple('Patch', ['var'])
match_err = object()
class Pattern:
def match(self, expr):
raise NotImplemented
def __repr__(self):
return self.__str__()
cl... |
#!/usr/bin/env python3
import sys, os
import re, struct
from argparse import ArgumentParser, FileType, Namespace
"""
======================== CONSTANTS ========================
"""
SUPPORTED_ROM = {
"cm": "cm.mk",
"lineageos": "lineage.mk",
"mokee": "mk___DEVICE__.mk",
"omnirom": "omni___DEVICE__.mk"... |
"""
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unico... |
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import gizmo_analysis as ga
import utilities as ga_ut
import sys
FIRE_elements = ['h','he','c','n','o','ne','mg','si','s','ca','fe']
FIRE_metals = ['c','n','o','ne','mg','si','s','ca','fe']
#
# wrapper to load data set a... |
from .models import Restaurante, Review, Evento
from main.forms import BusquedaPorNombre,BuscaTituloCuerpo
from django.shortcuts import render, redirect
from bs4 import BeautifulSoup
import urllib.request
import lxml
import re, os, shutil
import requests
import datetime
from whoosh.index import create_in,open_dir
from ... |
from pathlib import Path
import hydra
import numpy as np
import torch
from hydra.utils import to_absolute_path
from nnsvs.base import PredictionType
from nnsvs.mdn import mdn_loss
from nnsvs.pitch import nonzero_segments
from nnsvs.train_util import save_checkpoint, setup
from nnsvs.util import make_non_pad_mask
from ... |
from django.db import models
from django.db.models import Sum, Q
from django.utils import timezone
from decimal import Decimal
class LedgerAccount(models.Model):
"""A particular account in the accounting ledger system.
All transactions must have a left side (debit) and a right side (credit),
and they mu... |
# Clean data for predicting
import pandas as pd
import numpy as np
import scipy.sparse as sparse
import pickle
import os
import ipdb
import gc
from sklearn.cluster import MiniBatchKMeans
from joblib import Parallel, delayed
from departments import all_departments, top_upcs
train = test = labels = features = None
gr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.