text stringlengths 3.07k 22.1k |
|---|
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# Capriqorn --- CAlculation of P(R) and I(Q) Of macRomolcules in solutioN
#
# Copyright (c) <NAME>, <NAME>, and contributors.
# See the file AUTHORS.rst for the full list ... |
from typing import Optional, Union
from hpc.autoscale import hpclogging as logging
class _SharedLimit:
def __init__(
self,
name: str,
consumed_core_count: int,
max_core_count: int,
consumed_count: Optional[int] = None,
max_count: Optional[int] = None,
):
... |
from __future__ import division
import argparse
import matplotlib.pyplot as plt
import pickle
import gzip
import numpy as np
import tensorflow as tf
import matplotlib.gridspec as gridspec
import os
# from tensorflow.examples.tutorials.mnist import input_data
# np.set_printoptions(threshold=np.inf)
f =gzip.open('./scre... |
"""Implementation of the Monotonic RNNT Loss "Monotonic Recurrent Neural Network Transducer and Decoding Strategies", Tripathi et. al.
Inspired by @alexeytochin ctc loss implementation (github.com/alexeytochin/tf_seq2seq_losses/)
"""
from cached_property import cached_property
import tensorflow as tf
logger = tf.get_... |
from typing import List, Iterable, Mapping
from .common import write_varint, sha256
NIL = bytes([0] * 32)
def floor_lg(n: int) -> int:
"""Return floor(log_2(n)) for a positive integer `n`"""
assert n > 0
r = 0
t = 1
while 2 * t <= n:
t = 2 * t
r = r + 1
return r
def ceil_... |
import dataclasses
import inspect
import types
import warnings
from typing import Any, Awaitable, Callable, List, Optional, Tuple, TypeVar
import aiowamp
from aiowamp import URI
from aiowamp.args_mixin import ArgsMixin
from .entry_point import EventEntryPoint, ProcedureEntryPoint
__all__ = ["Handler",
"get... |
#!/usr/bin/python
#
#
# Vanderbilt University Computer Science
# Author: <NAME>
# Course: CS 6381 Distributed Systems Principles
# Created: Spring 2018
# Modified: Spring 2019 (to make compliant with Python 3)
#
# Purpose: Demonstrate Zookeeper Barrier Synchronization
#
# This is the Driver program
#
# Approach:
#
# ... |
#!/usr/bin/env python
"""Train a CNN for Google speech commands."""
__author__ = '<NAME>, <NAME>'
"""With modifications from Karan Goel."""
import argparse
import time
import torch
import torchvision
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.utils.data.sampler import Wei... |
#!/usr/bin/env python3
import os
from datetime import datetime
import time
import singer
# import json
import re
import collections
import inflection
import simplejson as json
from decimal import Decimal
from datetime import datetime
logger = singer.get_logger('target_athena')
def validate_config(config):
"""V... |
"""
The ``util`` module is used to contain utility functions and classes that have
practical utility within the context of this application but which could
conceivably be co-opted to serve in a different context for a different
application if needed. As such, there are no hardcoded magic numbers or any such
application... |
import arrow
import django_filters
from arrow.parser import ParserError
from django.core.exceptions import PermissionDenied
from rest_framework import viewsets, serializers, filters, exceptions, permissions, status, pagination
from rest_framework.response import Response
from django_filters.rest_framework import Django... |
# External
import math
import numpy
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from matplotlib.offsetbox import AnchoredText
# Local
from .utils import gaussian_fit, freq_content
plt.style.use('seaborn')
plt.rc('font', siz... |
# Group 3
# 03/04/2021
# const.py - ability to save an load changes
# CONSTANTS FILE -- VARIABLES THAT ARE USED THROUGH OUT THE PROGRAM, MOST UNCHANGED
# -- level_up() -- decides when the threshold for leveling up is, the numbers it returns will never change
# -- PLAYERS[] -- holds the players in the game.
i... |
import itertools
import math
import re
import json
from typing import List
from collections import defaultdict
from enum import Enum
WORD_LENGTH = 5
NUM_OF_TRIES = 6
# Hebrew meduyeket (מדויקת) data files
HEBREW_GUESSES_PATH = "database/hebrew_guesses.json" # 3k possible guesses
MEDUYEKET_SOLUTIONS_PATH... |
#!/usr/bin/python3
import sys
import json
def keys_per_signature(hashlen, otsbits):
return 2*(((hashlen*8-1) // otsbits)+1)
def sub_sub_keyspace_usage(hashlen, otsbits, height):
return 1 + keys_per_signature(hashlen, otsbits) * (1 << height)
def sub_keyspace_usage(hashlen, otsbits, heights):
usage = sub_... |
# Copyright (C) 2012 <NAME>. All Right Reserved.
import sys, os, hashlib, datetime, calendar
from datetime import timedelta
import MySQLdb as mdb
def gen_checksum(fn):
fh = open(fn, 'rb')
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(dat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 17:34:42 2018
@author: mohamed
"""
# =============================================================================
#
# =============================================================================
#from Zigzag import Zigzag
from Chain import *
... |
import numpy as np
import pandas as pd
from statsmodels.regression.lme import MixedLM
from numpy.testing import assert_almost_equal
from . import lme_r_results
from scipy.misc import derivative
from statsmodels.base import _penalties as penalties
import os
import csv
class R_Results(object):
"""
A class for h... |
import datetime
import os
import time
import torch
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
from detection.coco_utils import get_surfrider
from detection import transforms
from detection.centernet.models import create_model
from detection.losses import FocalLoss
from detection import... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import math
from collections import defaultdict
from heapq import *
def construct_lsalist(linkstate):
'''construct LSA list'''
lsalist = {}
for i in range(len(linkstate)):
if linkstate[i].get('Opaque-Type') == 4:
# Get SRGB
... |
from enum import Enum
from typing import Generator, NamedTuple
import pytest
from pms import SensorWarning
from pms.core import Sensor, Supported
@pytest.mark.parametrize("sensor", Supported)
@pytest.mark.parametrize("attr", ["Message", "Data", "Commands"])
def test_sensor_attrs(sensor, attr):
assert getattr(Se... |
# ----------------------------------------------------------------------
# Copyright (C) 2013 <NAME> <<EMAIL>>
# Copyright (C) 2014-2015 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as publi... |
from typing import Optional
from discord.ext import commands
from .utils import checks
from .utils.dataIO import DataIO
from discord import Member, Embed, Role, utils
import discord
from datetime import datetime,timedelta
import time
import re
from typing import Union
import json
class Userinfo(commands.Cog):
"""... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 09:58:50 2020
@author: duttar
Description: Solving the problem A = Bx
A is the timeseries stack of InSAR pixel wise
B is matrix including time and ADDT
x is a vector containing seasonal and overall subsidence
"""
import os
import numpy as n... |
from typing import Iterable
from svgwrite import Drawing
from svgwrite.container import Group
from svgwrite.shapes import Line, Rect
from svgwrite.text import Text
from stripes.models import SecondType
class TextTemplate:
def render_second(self, second_type):
return second_type.name
def render_grou... |
import asyncio
import inspect
import logging
import os
import signal
import socket
import sys
import threading
import traceback
from textwrap import wrap
from types import TracebackType
from typing import (IO, Dict, Any, Callable, Optional, Tuple, Generator, # noqa
List, Type, TypeVar, NamedTuple, ... |
# -*- coding: utf-8 -*-
"""
Conversion functions between various Chinese encodings and representations.
Notes
-----
Original methods and docs based upon `ltchinese`_, license `MIT`_ Steven
Kryskalla.
.. versionadded:: 0.1
Python 2/3 compatibility.
- PEP8, PEP257.
- ``int()`` casting for comparisons
-... |
"""
Author: <EMAIL>
Pretty printer for Amazon Textract AnalyzeExpense Response
Call the method as shown in below example to pretty print the AnalyzeExpense Response -
print(get_string(textract_json=data,output_type=[Textract_Expense_Pretty_Print.SUMMARY,Textract_Expense_Pretty_Print.LINEITEMGROUPS],
table_format=Pret... |
"""
-*- test-case-name: PyHouse.src.Modules.Comouter.Nodes.test.test_node_local -*-
@name: PyHouse/src/Modules/Computer/Nodes/node_local.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2014-2016 by <NAME>
@note: Created on Apr 2, 2014
@license: MIT License
@summary: Gather this node's informat... |
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views import Vi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
isoenum_webgui.routes
~~~~~~~~~~~~~~~~~~~~~
Isotopic enumerator web interface routes.
"""
import csv
import io
import json
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
from flask import jsonify
fro... |
#!/usr/bin/env python
# Filename: get_planet_image_list
"""
introduction: get images list of downloaded Planet image in time period and spatial extent
authors: <NAME>
email:<EMAIL>
add time: 16 July, 2020
"""
import sys,os
from optparse import OptionParser
sys.path.insert(0, os.path.expanduser('~/codes/PycharmProje... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
import argparse
import os
from pathlib import Path
from typing import Tuple
import pandas as pd
import category_encoders as ce
import yaml
import sys
from dotenv import load_dotenv
# from src.table import sentence_feature
load_dotenv() # noqa
sys.path.append(f"{os.getenv('PROJECT_ROOT')}src/") # noqa
ROOT = Path(o... |
from abc import abstractmethod
from datetime import datetime
from typing import TYPE_CHECKING, Dict, List, Optional, Type, cast
import pandas as pd
import pyarrow
from google.protobuf.json_format import MessageToJson
from feast.data_source import DataSource
from feast.dqm.profilers.profiler import Profile, Profiler
f... |
from collections import defaultdict
from functools import update_wrapper
from django import forms
from django.contrib.admin import ModelAdmin, SimpleListFilter, helpers
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.utils import unquote
from django.core.exceptions import P... |
# coding:utf-8
#!/usr/bin/python
#
# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
# -- This line is 75 characters -------------------------------------------
"... |
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright Holders: <NAME>, <NAME>, <NAME>
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
from collections import defaultdict
import numpy as np
from pymo... |
"""Utility to check the date and time in XML files generated by itktool.
NOTE: for generate win32 use: WINEARCH=win32 WINEPREFIX=~/win32 wine pyinstaller.exe --onefile xml_datetime.py
for run win32: WINEARCH=win32 WINEPREFIX=~/win32 sudo wine ./xml_datetime.exe
"""
try:
import xml.etree.cElementTree as ET
exc... |
import rinobot_plugin as bot
import re
import os
import numpy as np
_end_tags = dict(grid=':HEADER_END:', scan='SCANIT_END', spec='[DATA]')
class NanonisFile(object):
"""
Base class for Nanonis data files (grid, scan, point spectroscopy).
Handles methods and parsing tasks common to all Nanonis files.
... |
#! /usr/bin/env python3
"""
Copyright (c) 2010 - 2020, ETH Zurich, Computer Engineering Group
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 copy... |
# -*- coding: utf-8 -*-
"""
Keylogger Analysis Tool
=============================================================================
MIT License
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), t... |
from skeleton_parsing import skeleton_parser_str
from itertools import chain
import networkx as nx
def get_deppath_list(question_normal, ungrounded_nodes, isSkeletonorDep='Skeleton'):
abstract_question_deppath_list = []
final_ph_tok_list, link_anchor_list, ans_anchor = placeholding_node(question_normal.split(... |
import frappe
import json
import subprocess
from frappe import _
# User
def user_limit(self, method):
# JSON file path
json_file_path = frappe.get_site_path('quota.json')
# Reading File
with open(json_file_path) as jsonfile:
parsed = json.load(jsonfile)
count_website_users = parsed["count_website_... |
import operator
from collections import namedtuple
#
# Balanced binary tree based on Log-Balanced Search Trees (LBST)
# and slib's wttree
#
# ref: https://scholar.google.fr/scholar?cluster=16806430159882137269
#
LBST = namedtuple("LBST", "root")
Node = namedtuple("Node", "key value size left right")
_NODE_NULL = N... |
"""
Script that removes doubles from a .xml BLASTx output and converts it to a csv file
<NAME> & <NAME>
17/12/21
"""
# imports
from __future__ import division
from Bio.Blast import NCBIXML
import csv
import sys
import os
from lxml import etree
import pandas as pd
from collections import defaultdict
from datetime impo... |
from collections import defaultdict
from stoichiograph import speller
from stoichiograph.speller import Node
ELEMENTS = {
'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al',
'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe',
'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As... |
#!/usr/bin/env python3
import gym
import ptan
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
#from tensorboardX import SummaryWriter
from lib.SummaryWriter import SummaryWriter
from lib import common
from shohdi_lib import ShohdiExp... |
import boto3
import os
import subprocess
import sys
import getopt
import json
import datetime
import re
import webbrowser
import time
import configparser
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD... |
import numpy as np
from .base import Prior, PriorException
from .interpolated import Interped
from .analytical import DeltaFunction, PowerLaw, Uniform, LogUniform, \
SymmetricLogUniform, Cosine, Sine, Gaussian, TruncatedGaussian, HalfGaussian, \
LogNormal, Exponential, StudentT, Beta, Logistic, Cauchy, Gamma, ... |
from uuid import uuid4, UUID
from Bio.PDB.Atom import Atom
from Bio.PDB.Residue import Residue
class BoundingBox:
def __init__(self):
self.min_x = 1.0e+10
self.max_x = -1.0e+10
self.min_y = 1.0e+10
self.max_y = -1.0e+10
self.min_z = 1.0e+10
self.max_z = -1.0e+10
... |
from typing import List, Tuple, Union
import numpy as np
from z3 import And, Not
from quavl.lib.expressions.complex import ComplexVal
from quavl.lib.expressions.qbit import QbitVal
from quavl.lib.expressions.rqbit import RQbitVal
def qbit_equals_value(qbit: Union[QbitVal, RQbitVal], value: Tuple[Union[int, float], ... |
from sigpy.polys.polynomials import Polynomial
from sigpy.sage import sage_primal, sage_dual, sage_feasibility, hierarchy_e_k, relative_c_sage, relative_c_sage_star, \
relative_coeff_vector
import cvxpy
import numpy as np
from itertools import combinations_with_replacement
def sage_poly_dual(p, level=0):
sr, ... |
from sklearn.neighbors import LocalOutlierFactor
from pyod.models.iforest import IForest
from pyod.models.hbos import HBOS
from pyod.models.loda import LODA
from pyod.models.copod import COPOD
from tqdm import tqdm
import numpy as np
import pandas as pd
import os
import ast
import eval.evaluation_utils as utils
from sk... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import os
import json
import scipy
import scipy.stats
jian_file = 'result2'
grid_file = 'result2'
datasets = ['HGBn-ACM', 'HGBn-DBLP', 'HGBn-IMDB', 'HNE-PubMed', 'HGBn-Freebase', 'HGBn-ACM']
xL = [[[0, 1... |
from onegov.ballot import Candidate
from onegov.ballot import CandidateResult
from onegov.ballot import ElectionResult
from onegov.election_day import _
from onegov.election_day.formats.common import EXPATS, validate_integer
from onegov.election_day.formats.common import FileImportError
from onegov.election_day.formats... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# Author: <NAME>
class Board:
""" Board Class for Tic Tac Toe game """
"""
Methods -
---------
get_board()
end()
get_winner()
check_win()
available_moves()
update_x()
update_o()
... |
import abc
import os
from pkg_resources import resource_filename
from typing import Optional, List, Dict, Callable, Tuple
import base64
import asyncio
import shutil
import copy
from gtmcore.dataset.io import PushResult, PushObject, PullObject, PullResult
from gtmcore.dataset.manifest.manifest import Manifest, StatusRe... |
from tkinter import *
import PIL.Image, PIL.ImageTk
import time
import random
#screen class to handle the GUI
class Screen():
def __init__(self):
self.canvas = Canvas(root, height=600, width=600, relief=RAISED, bg="white")
self.numPlayers = 1
self.word = ' '
self.progress = 0 #pro... |
#!/usr/bin/env python
#!/usr/bin/env python
#**************************************************************************************
#**************************************************************************************
# ants_seg_to_nidm.py
# License: GPL
#************************************************************... |
from prettytable import PrettyTable
import pandas as pd
from .column import Column, ColumnSet
from .query_templates import query_templates
class Table(object):
"""
A Table is an in-memory reference to a table in a database. You can use it to get more info
about the columns, schema, etc. of a table and you ... |
import discord
import asyncio
from discord.ext import commands
from Components.MangoPi import MangoPi
from Components.RaidFilter import RaidFilter
def setup(bot: MangoPi):
"""
Function necessary for loading Cogs. This will update AntiRaid's data from mongoDB.
Parameters
----------
bot : MangoPi
... |
"""
Basic Python client for creating My Organization compatible data from VIVO.
"""
import requests
import logging
import os
import random
import csv
import re
import sys
import argparse
import logging
import time
# Python 2 or 3
PYV = sys.version_info
if PYV > (3, 0):
from urllib.request import urlopen, Request
... |
import os
import sys
import keras
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.callbacks import CSVLogger, History
from keras.layers import BatchNormalization, Dense, Dropout, Input
from keras.models import Model
# from .IntegratedGradient import integrated... |
#!/usr/bin/env python3
"""
Generates API documentation for the Labelbox Python Client in a form
tailored for HelpDocs (https://www.helpdocs.io). Supports automatic
uploading of generated documentation to Labelbox's HelpDocs pages,
if given a HelpDocs API Key for Labelbox with write priviledges. Otherwise
outputs the g... |
"""Windows of the videotracker"""
import os
import inspect
#import importlib
from PyQt5 import QtWidgets, QtCore, QtGui
#import cv2
from . import helpers, segmentations, widgets
class ModuleDialog(QtWidgets.QDialog):
"""A dialog for choosing a module"""
def __init__(self, *args, **kwargs):
super(... |
import urllib.parse
import re
import arrow
import uuid
from utils.constants import INTERVAL_MAPPING, MIN_PASSWORD_LENGTH, \
CVE_INDEX, CVE_SCAN_LOGS_INDEX, TABLE_COLUMN_NON_TEXT_FIELD
def get_epochtime():
time_now = arrow.now()
return int(time_now.timestamp()) * 1000 + time_now.microsecond
def get_eula... |
from collections import defaultdict
from typing import Dict, Sequence, Tuple
import numpy as np
from ..dataset import MotionPredictionDataset
from ..proto import (ObjectPrediction, Submission, Trajectory, Vector3,
WeightedTrajectory)
from ..utils.map import repeated_points_to_array
from .metrics ... |
"""
Merge predictions
"""
from __future__ import division
from shapely.geometry import MultiPolygon
from pylab import *
import pandas as pd
rcParams['figure.figsize'] = 20, 20
def stretch_8bit(bands, lower_percent=2, higher_percent=98):
out = np.zeros_like(bands).astype(np.float32)
for i in range(3):
... |
# Adapted from https://github.com/ArrowLuo/CLIP4Clip/blob/668334707c493a4eaee7b4a03b2dae04915ce170/main_task_retrieval.py#L457
import os
import sys
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
import numpy as np
from evaluation.metrics import compute_metrics
from evaluation.metrics import tensor_text_to... |
""" from https://github.com/keithito/tacotron """
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the foll... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import functools
import os
import re
import shutil
import subprocess
import zipfile
from argparse import ArgumentParser, Namespace, _SubParsersActio... |
from matplotlib.ticker import PercentFormatter
from scipy.stats import skew, kurtosis
from typing import Tuple
import matplotlib.pyplot as plt
import pandas as pd
__all__ = [
'univariate_plot',
'univariate_plot_v2',
'boxplot_summary',
'pareto_plot',
]
def univariate_plot_v2(independent_variable: pd.... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: self_training_validation.py
# @Author: <NAME>
# @Time: 23/1/22 17:09
import csv
import logging
import os
import sys
import time
from math import floor
from os import walk
import numpy as np
import yagmail
from sklearn.metrics import f1_score, me... |
import maya.cmds as cmds
import random
import functools
random.seed(1234)
# default values
TARGET_CENTER = [0, 0, 0]
INSTANCE_AMOUNT = 50
TARGET_AREA_GLOBAL_RANGE = [float(20), float(10), float(20)]
TARGET_GLOBAL_RANDOMNESS = 0.8
TARGET_GLOBAL_THRESHOLD = 0.8
TARGET_GLOBAL_MOVE_DURATION_MIN = 500
TARGET_GLOBAL_MOVE_... |
from os import error
from instagrapi import Client
from flask import Flask,jsonify
import json
import random
print('Login in..')
def write_file(data, filename):
fh = open(filename, "w")
try:
fh.write(json.dumps(data))
finally:
fh.close()
def read_file(filename):
fh = open(filename, "r... |
import os
import atexit
import signal
import numpy as np
import tensorflow as tf
from subprocess import Popen, PIPE
from glearn.utils.log import log, log_warning
from glearn.utils.path import remove_empty_dirs
from glearn.utils import tf_utils
SUMMARY_KEY_PREFIX = "_summary_"
DEFAULT_EVALUATE_QUERY = "evaluate"
DEFAU... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
# The MIT License (MIT)*************
#
#
# Copyright (c) 2013 mato.sus304(<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 without limitation t... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings; warnings.simplefilter('ignore')
from scipy import stats
from ast import literal_eval
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kern... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : recording.py
# Author : <NAME>, <NAME>
# Email : <EMAIL>, <EMAIL>
# Date : 03.08.2019
# Last Modified Date: 27.08.2019
# Last Modified By : Chi Han, Jiayuan Mao
#
# This file is part of the VCML codebase
# Distribu... |
# Thank you https://github.com/leemengtaiwan/tiny-imagenet/blob/master/TinyImageNet.py
# Libraries
import os
import glob
import torch
from torch.utils.data import Dataset
from PIL import Image
from torchvision import transforms
from datasets.dataset_setup import DatasetSetup
from my_utils.utils import train_val_spli... |
import math
import re
import os
import collections
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.nn.functional as F
from torch.autograd import Variable
from .VideoTransforms import ClipDenseSpatialCrop
from .Gdn import Gdn3D
fr... |
import web
import tempfile
import os
import subprocess
import xmltodict
import json
import cgi
import shutil
from extractor.extractionWrapper import Extraction
from extractor.utilities import Util
urls = (
'/', 'Index',
'/extractor', 'FileHandler', # For uploading a file
'/extractor/file', 'PDFStreamHandler', # For ... |
from multi_fits_cubes.cloud import Cloud
import numpy as np
from spectral_cube import SpectralCube
from collections import OrderedDict
import astropy.units as u
from astropy.wcs import WCS
kps = u.km / u.s
class FluxRMS(Cloud):
def __init__(self, signal_v_range, *args, **kwargs):
super().__init... |
import pytest
from bitey.cpu.addressing_mode import (
AbsoluteAddressingMode,
AbsoluteXAddressingMode,
AbsoluteYAddressingMode,
AccumulatorAddressingMode,
ImmediateAddressingMode,
ImpliedAddressingMode,
IndexedIndirectAddressingMode,
IndirectIndexedAddressingMode,
RelativeAddressingM... |
import altair as alt
from altair.utils import parse_shorthand as alt_parse_shorthand
import pandas as pd
from typing import (
Dict as DictType,
List as ListType,
Optional as OptionalType,
Tuple as TupleType,
Union as UnionType,
)
from csvviz import altUndefined
from csvviz.exceptions import Invalid... |
"""Functions for editing a folder"""
from ..ski import skiboot, read_json
from ..ski.excepts import ServerError
from . import project_loaded, item_info, ident_exists
def _get_folder(project, foldernumber):
"""On success return (deep copy of folder, empty string)
on failure return (None, failure string)... |
import os
import torch
import scipy
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.preprocessing import StandardScaler
from imblearn.under_sampling import Random... |
import collections
import gzip
import json
import logging
import os
import work_queue as wq
from lobster import util
from lobster.core.dataset import FileInfo
import unit
from WMCore.DataStructs.LumiList import LumiList
__all__ = ['TaskHandler', 'MergeTaskHandler', 'ProductionTaskHandler']
logger = logging.getLogge... |
"""Implementation of LinkedList class."""
from __future__ import annotations
from collections.abc import MutableSequence
from dataclasses import dataclass, field
from typing import Generic, Iterable, Iterator, Tuple, TypeVar
from dataslots import with_slots
LINKED_LIST_HEAD = object()
T = TypeVar('T')
@with_slot... |
# 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 use ... |
from metrics import compute_precision_and_recall, compute_confusion_matrix
from metrics import compute_f1_measure, compute_accuracy
from data import load_data, train_test_split
import numpy as np
import copy
from visualize import plot_decision_regions
try:
import matplotlib
import matplotlib.pyplot as plt
exce... |
#!/usr/bin/env python3
import argparse
import hashlib
import io
import logging
import os
import subprocess
import sys
DRY_RUN=True
DEBUG_LEVEL=30
class FileSystemEntry:
source = ""
target = ""
mtype = ""
options = ""
freq = ""
passno = ""
def __str__(self):
return self.sou... |
"""
Cpp solution with explanation in details
It's a very classical question.
Ref: http://www.geeksforgeeks.org/partition-set-k-subsets-equal-sum/
class Solution {
public:
// Method returns true if nums can be partitioned into K subsets
// with equal sum
bool canPartitionKSubsets(vector<int>& nums, int K)... |
# -*- coding: utf-8 -*-
"""
@File: database.py
@Description: This is a module for different database operations and
to provide a fast lookup.
This application,
1. Open/Close a SQLite database connection
2. Create a new SQLite dat... |
#This file implements the upHRP algorithm, the MinVAr portfolio and the InvLamda portf.
#Code for classical HRP is based on <NAME>. (2018). Advances in Financial
#Machine Learning. Wiley. The code has been modified to create an uplifted portfolio
#strategies based on FRM adjacency mtrices and its adapted in order to b... |
import inspect
from enum import Enum
from typing import (
Any, AnyStr, ClassVar, Dict, List, Literal, Optional, Tuple, Type, Union,
get_args, get_origin
)
from typing_extensions import Annotated
from ...errors import CommandSetupError
from ...models import InteractionChannel, InteractionMember, InteractionUse... |
import os
import re
import subprocess
from collections import namedtuple
import logging
import bisect
from common import SushiError, get_extension
import chapters
MediaStreamInfo = namedtuple('MediaStreamInfo', ['id', 'info', 'default', 'title'])
SubtitlesStreamInfo = namedtuple('SubtitlesStreamInfo', ['id', 'info', ... |
import smbus
import gevent
from gevent.lock import BoundedSemaphore
from Node import Node
READ_ADDRESS = 0x00
READ_RSSI = 0x01
READ_FREQUENCY = 0x03
READ_TRIGGER_RSSI = 0x04
READ_LAP = 0x05
READ_TIMING_SERVER_MODE = 0x06
WRITE_TRIGGER_RSSI = 0x53
WRITE_FREQUENCY = 0x56
WRITE_TIMING_SERVER_MODE = 0x57
UPDATE_SLEEP =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.