input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
are useless." % ",".join(memeber_set))
class AiAnalysisTaskClassificationOutput(AbstractModel):
"""智能分类结果信息
"""
def __init__(self):
"""
:param ClassificationSet: 视频智能分类列表。
:type ClassificationSet: list of MediaAiAnalysisClassificationItem
"""
self.ClassificationSet = None
def _deserialize(self, params)... | |
import argparse
import cv2 as cv
import numpy as np
import os
"""
Link to original paper : https://arxiv.org/abs/1812.11703
Link to original repo : https://github.com/STVIR/pysot
You can download the pre-trained weights of the Tracker Model from https://drive.google.com/file/d/11bwgPFVkps9AH2NOD1zBDdpF_tQghA... | |
import re
import math
import numpy as np
class UpstreamAUG:
def __init__(self, allow_ORF=True, verbose_output=False):
"""
Constructor
:param allow_ORF: bool, True by default, whether to check uORFs
:param verbose_output: bool, False by default, whether to return dictionaries in predict_on_sample() and predict_o... | |
<gh_stars>1-10
"""
Steenrod algebra bases
AUTHORS:
- <NAME> (2008-07-30): version 0.9
- <NAME> (2010-06-30): version 1.0
- <NAME> (2011-10-25): Fix the use of cached functions
This package defines functions for computing various bases of the
Steenrod algebra, and for converting between the Milnor basis and
any other... | |
<filename>Tools/config.py<gh_stars>1-10
#=======================================================================
# Copyright <NAME> 2015.
# Distributed under the MIT License.
# (See accompanying file license.txt or copy at
# http://opensource.org/licenses/MIT)
#==========================================================... | |
r"""
=========================================================
Utilities Abaqus (:mod:`desicos.abaqus.abaqus_functions`)
=========================================================
.. currentmodule:: desicos.abaqus.abaqus_functions
Includes all utilities functions that must be executed from Abaqus.
"""
from __future__... | |
<gh_stars>100-1000
# Copyright (c) 2018 Intel Corporation
# Copyright (c) 2019, NVIDIA CORPORATION. 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.... | |
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateCaptureRequest(AbstractModel):
"""CreateCapture请求参数结构体
"""
def __init__(self):
r"""
:param Data: 原始抓拍报文
:type Data: str
"""
self.Data = None
def _deserialize(self, params):
self.Data = params.get("Data")
memeber_set =... | |
"""
# Handle inputs and derive some useful parameters from them
log10T_in = np.log10(temperature_K)
T_in_keV = temperature_K / 11604518 # Convert temperature from K to keV.
# Get energy bins centers based on geometric mean.
energy_gmean_keV = stats.gmean(np.vstack((energy_edges_keV[:-1], energy_edges_keV[1:])))
... | |
pbParam.velocityRatio = velocityRatio
pbParam.accelerationRatio = accelerationRatio
queuedCmdIndex = c_uint64(0)
# 滑轨的特殊处理
if slaveDevType == DevType.Magician:
while(True):
result = api.SetPTPCommonParams(c_int(masterId), c_int(slaveId), byref(pbParam), isQueued, byref(queuedCmdIndex))
if result != DobotCommun... | |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from collections import defaultdict
from time import time
from kafka import KafkaAdminClient, KafkaClient
from kafka import errors as kafka_errors
from kafka.protocol.offset import OffsetRequest, OffsetResetStr... | |
<filename>nzekenovhw8.py
import tkinter
from tkinter import messagebox
import socket
def StartConnection (IPAddress, PortNumber):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((IPAddress,PortNumber))
return server
#this function moves binary values to the left (part of hashing)
def left... | |
<reponame>virdesai/stock-analysis-engine
"""
TA-Lib wrappers
"""
# for unittests, allow passing the mocks into the runtime if not found
try:
import talib as ta
except Exception:
import analysis_engine.mocks.mock_talib as ta
# end of loading talib or mocks
import spylunking.log.setup_logging as log_utils
log = log_u... | |
# python3 -m pip install isort autoflake astpretty black
# requires python3.9 to run
import os
import argparse
import ast
import subprocess
import multiprocessing
from pathlib import Path
import astpretty
import sys
parser = argparse.ArgumentParser()
parser.add_argument(
"--out_dir", type=str, default="python",
)
par... | |
struct nx_action_sample */
NXAST_SET_MPLS_LABEL = 30, # /* struct nx_action_ttl */
NXAST_SET_MPLS_TC = 31 # /* struct nx_action_ttl */
)
nx_stats_subtype = enum('nx_stats_subtype', globals(), uint32,
NXST_FLOW = 0,
NXST_AGGREGATE = 1,
NXST_FLOW_MONITOR = 2
)
def create_ofs_nbits(ofs, n_bits):
return (ofs ... | |
2
xlVerbPrimary = 1
# XlCalculation
xlCalculationAutomatic = -4105
xlCalculationManual = -4135
xlCalculationSemiautomatic = 2
# XlFileAccess
xlReadOnly = 3
xlReadWrite = 2
# XlEditionType
xlPublisher = 1
xlSubscriber = 2
# XlObjectSize
xlFitToPage = 2
xlFullPage = 3
xlScreenSize = 1
# XlLookAt... | |
#!/usr/bin/env python3
# Author: <NAME>
import os
import os.path as osp
import time
from typing import Any, Dict, List, Optional
from sklearn.metrics import r2_score, explained_variance_score
import h5py
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from pytorch_transformers impor... | |
<filename>ppq/IR/morph.py
from typing import Any, List
import numpy as np
import torch
from ppq.core import (DataType, TargetPlatform,
convert_any_to_python_primary_type,
convert_any_to_torch_tensor, ppq_warning)
from ppq.IR.quantize import DeviceSwitchOP
from ppq.IR.search import SearchableGraph
from ppq.scheduler ... | |
import sys
sys.path.insert(0, '../reports/code_blocks')
import ref_help as mv
def get_lgts(head, tail, sol, forcefield):
if forcefield == 'martini':
nc3 = {'N': 1, 'C': 5, head: 13}
po4 = {'P': 1, 'O': 4}
gl1 = {'C': 2, 'O': 2, tail: 2}
gl2 = {'C': 3, 'O': 2, tail: 3}
c1a = {'C': 5, tail: 10}
c2a = {'C': 4, tai... | |
<gh_stars>1-10
from typing import Any, Callable, List, Optional
import torch
import torch.distributed as dist
from torch.distributed.optim import ZeroRedundancyOptimizer
from torch.distributed.optim.zero_redundancy_optimizer import _OverlapStatus
from torch.nn.parallel.distributed import DistributedDataParallel
# Fun... | |
from rpython.annotator import model as annmodel, unaryop, binaryop, description
from rpython.flowspace.model import Constant
from rpython.rtyper.error import TyperError, MissingRTypeOperation
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.lltypesystem.lltype import Void, Bool, LowLevelType
from rpyt... | |
and not self.config.tie_word_embeddings:
old_lm_head = self.get_output_embeddings()
new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens)
self.set_output_embeddings(new_lm_head)
return self.get_input_embeddings()
def _get_resized_embeddings(
self, old_embeddings: nn.Embedding, new_num_tokens: Opt... | |
"threads_per_core", value)
@pulumi.input_type
class InstanceCreditSpecificationArgs:
def __init__(__self__, *,
c_pu_credits: Optional[pulumi.Input[str]] = None):
if c_pu_credits is not None:
pulumi.set(__self__, "c_pu_credits", c_pu_credits)
@property
@pulumi.getter(name="cPUCredits")
def c_pu_credits(self) -... | |
<reponame>katerinazuzana/sign-language-dictionary<filename>dictionary/drawing_canvas.py
import tkinter as tk
import math
import cmath
class DrawingCanvas(tk.Canvas):
"""A canvas used to select an eliptic area on the background picture.
An ellipse can be draw on the canvas. The ellipse can then be moved,
resized a... | |
an older version of
# Python that cannot validate certificates encrypted with SHA-2. If it is, then
# fall back on disabling the certificate validation and try again - unless the
# SHOTGUN_FORCE_CERTIFICATE_VALIDATION environment variable has been set by the
# user. In that case we simply raise the exception. Any o... | |
import random
from flask import Flask, request, redirect, render_template, session, flash
import cgi
from StringSigFigs import MakeNumber, RoundValue, CheckAnswer, CheckRounding, ApplySciNotation
from CalcsWithSigFigs import addValues, subtractValues, multiplyValues, divideValues, findDecimalPlaces, addWithPlaceholders... | |
import argparse
import base64
import datetime
import json
import logging
import sys
import uuid
import flask
import jwt
from flask import Response
from flask_babel import lazy_gettext as _
from jwt.algorithms import HMACAlgorithm
from sqlalchemy.orm.session import Session
from api.base_controller import BaseCirculati... | |
<filename>collect.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
import json
import csv
from datetime import date, datetime
from hashlib import sha1
import botocore
import boto3
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(loggi... | |
<filename>pandas/tests/reshape/concat/test_datetimes.py
import datetime as dt
from datetime import datetime
import dateutil
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
Timestamp,
concat,
date_range,
to_timedelta,
)
import pand... | |
<gh_stars>1-10
from hityper.tdg import *
from hityper.typeobject import *
from hityper import logger
from hityper.stdtypes import builtin_method_properties, stdtypes, inputtypemap
import ast
from copy import deepcopy, copy
import sys, getopt
from pycg.pycg import CallGraphGenerator
from pycg import formats
from pycg.u... | |
<reponame>mit-han-lab/torchquantum
import torch
import torch.nn as nn
import torchquantum as tq
import torchquantum.functional as tqf
import numpy as np
from enum import IntEnum
from torchquantum.functional import mat_dict
from torchquantum.quantization.clifford_quantization import CliffordQuantizer
from abc import AB... | |
msg.raw[:msglen.value]
def crypto_sign_verify_detached(sig, msg, pk):
if None in (sig, msg, pk):
raise ValueError
if len(sig) != crypto_sign_BYTES:
raise ValueError("invalid sign")
if not (len(pk) == crypto_sign_PUBLICKEYBYTES): raise ValueError('Truncated public key')
__check(sodium.crypto_sign_verify_detached... | |
from zeropdk.layout import insert_shape
from zeropdk.layout.geometry import cross_prod, project, rotate90
import klayout.db as kdb
def box(point1, point3, ex, ey):
"""Returns a polygon of a box defined by point1, point3 and orientation ex.
p2 ----- p3
| |
p1 ----- p4
ex --->
"""
point2 = project(point3 - po... | |
<reponame>arcticmatter/pipresents-beep
"""
HTML parser
"""
import os
import webbrowser
import tkinter as tk
from tkinter import font
from copy import deepcopy
from PIL import Image, ImageTk
from html.parser import HTMLParser
from collections import OrderedDict
#________________________________________________________... | |
'''IndexedFasta.py - fast random access in fasta files
===================================================
This module provides fast random access to :term:`fasta` formatted
files that have been previously indexed. The indexing can be done
either through the samtools faidx tool (accessible through pysam_) or
using the... | |
g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribeTopClientIpSumInfoList(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = Http... | |
self.get_nhg_id('group2')
# Test scenario:
# - update the route created in `test_remove_referenced_nhg` to own the NHG with the same details as the
# previous one and assert a new NHG and 2 new NHGMs are added
# - update the route to point back to the original NHG and assert the routeOrch's owned NHG is deleted
d... | |
rating == None or rating == '0.0': rating = '0'
rating = rating.encode('utf-8')
try: votes = str(item['votes'])
except: votes = '0'
try: votes = str(format(int(votes),',d'))
except: pass
if votes == None: votes = '0'
votes = votes.encode('utf-8')
try: mpaa = item['certification']
except: mpaa = '0'
if mpaa ... | |
# -*- coding: utf-8 -*-
# Owner(s): ["oncall: jit"]
import torch
# This is how we include tests located in test/jit/...
# They are included here so that they are invoked when you call `test_jit.py`,
# do not run these test files directly.
from jit.test_tracer import TestTracer, TestMixTracingScripting # noqa: F401
fr... | |
<filename>jdma_control/backends/FTPBackend.py
"""Class for a JASMIN Data Migration App backend that targets a FTP server
using the Python ftplib
Creating a migration on a ftp server consists of the following
operations:
1. Create a directory for the group workspace and current batch id, as an
identifier
2. Uploa... | |
'tuf.roledb.py', raise an exception.
if not tuf.roledb.role_exists(rolename):
raise tuf.Error(repr(rolename) + ' not in "tuf.roledb".')
# Keep track of the keys loaded to avoid duplicates.
keyids = []
# Generate keys for the keyids listed by the role being processed.
for keyid in tuf.roledb.get_role_keyids(rol... | |
= bed_dict['all']['real'].cat(bed_dict[region]['real'], stream=True, postmerge=False).saveas()
#saves offsets so after shuffling the offsets can be readjusted
offset_dict = get_offsets_bed12(bed_dict[region]['real'])
for i in range(nrand):
random_intervals = bed_dict[region]['real'].shuffle(genome=short_species, i... | |
import os
import numpy as np
from warnings import warn
from Utility import timer
import shutil
class BaseProperties:
def __init__(self, casename, casedir='.', filename_pre='', filename_sub='', ensemblefolder_name='Ensemble', result_folder='Result', timecols='infer', time_kw='ime', force_remerge=False,
debug=False, *... | |
/ %s!',
server_id, server.pid, pid)
lock.release()
continue
if server_task:
if server.status == 'pending':
server.status = 'running'
else:
pycos.logger.warning('Invalid status %s for server %s', server.status, server.sid)
lock.release()
else:
lock.release()
# assert server_task is None
if server.status == ... | |
_callback=self.callback,
silent=self.silent)
elif d_type == 'release':
ioc_clean.IOCClean(silent=self.silent).clean_releases()
ioc_common.logit(
{
'level': 'INFO',
'message': 'All iocage RELEASE and jail datasets have been'
' destroyed.'
},
_callback=self.callback,
silent=self.silent)
elif d_type == 'templa... | |
0 7 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 3 0 0 0 0 0 2 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 3 0 0 0]]
Output:
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 7 0 0 0 0 0 0 0 0 0 0 0]
[0 0 7 1 7 0 0 0 ... | |
<gh_stars>1-10
# pylint: disable=too-many-lines
from collections.abc import Sequence
from datetime import datetime
from enum import auto, Flag
from typing import Optional, List, Tuple
from dataclasses import dataclass, field
from triple_agent.classes.action_tests import ActionTest
from triple_agent.classes.books impor... | |
<filename>function_pipe.py
"""
function_pipe.py
Copyright 2012-2017 Research Affiliates
Authors: <NAME>, <NAME>, <NAME>
Common usage:
import function_pipe as fpn
"""
import functools
import inspect
import re
import sys
import types
from enum import Enum
import numpy as np
# ---------------------------------------... | |
<reponame>deadsnakes/python2.4
# This script generates a Python interface for an Apple Macintosh Manager.
# It uses the "bgen" package to generate C code.
# The function specifications are generated by scanning the mamager's header file,
# using the "scantools" package (customized for this particular manager).
#
# XXXX... | |
#!/usr/bin/env python
ANSIBLE_METADATA = {
'metadata_version': '2.0',
'supported_by': 'community',
'status': ['preview']
}
DOCUMENTATION = '''
---
module: ovh
short_description: Manage OVH API for DNS, monitoring and Dedicated servers
description:
- Add/Delete/Modify entries in OVH DNS
- Add reverse on OVH dedi... | |
item.xpath(xpEngagedDate, namespaces = self.nsmap), 'text')
existence_test_and_add(self, 'engaged_date_date_collected', item.xpath(xpEngagedDateDateCollected, namespaces = self.nsmap), 'attribute_date')
existence_test_and_add(self, 'engaged_date_data_collection_stage', item.xpath(xpEngagedDateDataCollectionStage, nam... | |
YOU TO PUNCH GHOSTS->(R)Ghost Punching Gloves]]"
}
],
"hooks": [],
"cleanText": "You take out the nearest robot guard and disguised yourself as one of them. You walk towards the security room. Waving and saying wassup to the other robot guards trying to blend in. This works and you make it to the front door. Yo... | |
the direction i.
d: float or arr
Superconductor paring amplitud.
-If d is a float, d is the Rashba coupling along the y-direction,
with the same value in every site.
-If d is a 2D array, each element of the array is the on-site
superconducting paring amplitud
space: {"position","momentum"}
Space in which t... | |
<reponame>eaton-lab/physeqs<filename>ipcoal/utils/utils.py
#!/usr/bin/env python
"""
Miscellaneous functions
"""
from typing import Tuple, Optional
import time
import datetime
import itertools
import toytree
import numpy as np
import pandas as pd
from numba import njit
from ipcoal.utils.jitted import count_matrix_in... | |
<filename>prog_ex/foobar/find-the-access-codes.py
def solution(l):
"""
Solution 4 again passes all but the last test case. Try to speed things
up some using a dynamic programming-like approach.
This solution wound up passing all of the test cases -- the key here is to
uses a memorization/dynamic programming appro... | |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import xml.etree.cElementTree as ET
from operator import itemgetter
from collections import OrderedDict
import sys, getopt
import json
# Get entityID
def getEntityID(EntityDescriptor, namespaces):
return EntityDescriptor.get('entityID')
# Get MDUI Descriptions
def g... | |
"""
You have to write the perc_train function that trains the feature weights using the perceptron algorithm for the CoNLL 2000 chunking task.
Each element of train_data is a (labeled_list, feat_list) pair.
Inside the perceptron training loop:
- Call perc_test to get the tagging based on the current feat_vec and ... | |
= sig.bind(*args, **kwargs)
bound_args.apply_defaults()
keepTop = bound_args.arguments["keepTop"]
keepBottom = bound_args.arguments["keepBottom"]
if (not keepTop) and (not keepBottom):
raise ValueError("You have to keep at least one half")
solid = self.findSolid()
maxDim = solid.BoundingBox().DiagonalLength ... | |
%%
import subprocess
from subprocess import Popen, PIPE, STDOUT
cmd = 'ls /etc/fstab /etc/non-existent-file'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
print(output)
# %%
import sys
print('a')
print(sys.stdout)
# %%
# from pathlib import Path
#
#... | |
= self._test_volte_mt_mt_add_volte_swap_x(0)
if call_ab_id is None or call_ac_id is None:
return False
return self._test_ims_conference_merge_drop_first_call_from_host_cep(
call_ab_id, call_ac_id)
@TelephonyBaseTest.tel_test_wrap
def test_volte_mo_mo_add_wcdma_merge_drop_second_call_from_participant_no_cep(
se... | |
= [1] + placed + [(p - 1) for p in placed] + [(p + 1) for p in placed
]
queue = sorted(set(queue))
seen = set(queue)
while queue:
lowest = queue.pop()
if lowest == 0:
continue
needed_budget = (37 - len(placed)) * lowest
for p in placed:
needed_budget += max(0, lowest - p)
if budget < needed_budget:
continue... | |
# Elastic search mapping definition for the Molecule entity
from glados.es.ws2es.es_util import DefaultMappings
# Shards size - can be overridden from the default calculated value here
# shards = 3,
replicas = 0
analysis = DefaultMappings.COMMON_ANALYSIS
mappings = \
{
'properties':
{
'_metadata':
{
'propertie... | |
import logging
import pickle
import random
from collections import Counter
from itertools import chain, permutations
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from snorkel.analysis import Scorer
from sn... | |
( fill_colour.red(), fill_colour.green(), fill_colour.blue() )
dictionary_part[ 'colours' ][ colour_type ] = ( border_rgb, fill_rgb )
return dictionary_part
class _ServiceRatingsNumericalPanel( ClientGUICommon.StaticBox ):
def __init__( self, parent, dictionary ):
ClientGUICommon.StaticBox.__init__... | |
#!/usr/bin/env python3
import re
import sys
import pprint
import getopt
pp = pprint.PrettyPrinter(indent=4)
prefix = None
pmgfiles = list()
outfile = None
debug = False
genhdr = False
opts, args = getopt.getopt(sys.argv[1:], "p:o:dg")
for o, a in opts:
if o == "-p":
prefix = a
elif o == "-o":
outfile = a
elif... | |
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[6, 6, 6,... | |
a bit weird because the main mechanism is a file write...
"""
if logger is None: logger=self.logger
log = logger.getChild('prep_cf')
wrkr = self._get_wrkr(Preparor)
#copy the template
wrkr.tag = '%s_%s'%(self.name, self.tag)
cf_fp = wrkr.copy_cf_template() #just copy the default template
#==============... | |
device=x.device)).any(1)]
# Apply finite constraint
# if not torch.isfinite(x).all():
# x = x[torch.isfinite(x).all(1)]
# If none remain process next image
n = x.shape[0] # number of boxes
if not n:
continue
# Sort by confidence
# x = x[x[:, 4].argsort(descending=True)]
# Batched NMS
c = x[:, 5:6] * (0 i... | |
an issue for the forked adjutant
# horizon
data = {'email': "<EMAIL>", 'username': 'test_user'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json()['notes'],
['If user with email exists, reset token will be issued.'])
... | |
<filename>pose_classification_kit/src/dataset_controller.py<gh_stars>10-100
import os
import numpy as np
from datetime import date
import numpy as np
from pathlib import Path
import json
from .imports.qt import QtWidgets, QtCore, QtGui, pyqtSignal, pyqtSlot
from .imports.openpose import OPENPOSE_LOADED
if OPENPOSE_LO... | |
type so the value written to the database is only
# down to the second.
value = value.replace(microsecond=0)
self.cursor.execute("create table t1(t time)")
self.cursor.execute("insert into t1 values (?)", value)
result = self.cursor.execute("select t from t1").fetchone()[0]
self.assertEqual(type(result), time)
... | |
<filename>ape_tabular.py<gh_stars>0
import copy
import re
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import roc_auc_score, f1_score
from sklearn.linear_model import LinearRegression, LogisticRegression
from yellowbrick.cluster import KElbowVisualizer
from anchors impo... | |
information. Skipped.",
2,
)
return
vgg_train_labels = np.argmax(y_train, axis=1)
gen_train_data = self.generate_new_data(
len(vgg_train_labels),
labels=vgg_train_labels,
num_classes=num_classes,
)
train_generator = SimpleConditionalDataGenerator(
gen_train_data,
y_train,
vgg_batch_size,
True,
)
tes... | |
len(Knovel) - 1]).
Exemplars: a list of length len(Knovel) * nExemplars of 2-element
tuples. The 1st element of each tuple is the image id that was
sampled and the 2nd element is its category label (which is in
the ragne [nKbase, nKbase + len(Knovel) - 1]).
"""
if len(Knovel) == 0:
return [], []
nKn... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME>
# email: <EMAIL>
"""
Group astronomical images by fields and epochs.
Example of usage:
python stacking.py --path_data pathtoyourdata/ --radius 10 --deltaT 1
will stack all images in pathtoyourdata/ whose referenced RA and Dec
(CRVAL1 and CRVAL2) are se... | |
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None
# PaSST
# refer to https://arxiv.org/abs/2110.05069 Section 2
self.new_pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) # for C and D tokens
self.freq_... | |
slc.start)
def slice_up_range(n, num_slices, start=0):
"""
Divides up `range(start,start+n)` into `num_slices` slices.
Parameters
----------
n : int
The number of (consecutive) indices in the range to be divided.
num_slices : int
The number of slices to divide the range into.
start : int, optional
The st... | |
"""LUNOS Heat Recovery Ventilation Fan Control (e2/eGO)"""
# FIXME: can we subscribe to updates from the w1/w2 entities to avoid polling?
import asyncio
import logging
import time
import voluptuous as vol
from homeassistant.components.fan import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SPEED_HIGH,
SPEED_LOW,
SPEED_M... | |
colour ranges
# # extract coeffs from fit logs via:
# # awk 'BEGIN {print("coeffs = {")} /POLYFIT/{ if($3~/sdss_psfmag/){pe="p"} else if ($3~/sdss_fiber2mag/){pe="e"} else{pe="error"}; printf("\"%s%d_%s\": %s,\n", substr($3,length($3)), $8, pe, $10)} END {print("}")}' bhm_spiders_agn_gaiadr2_pontlike/gdr2_*mag_to_sds... | |
<reponame>andriyor/featuretools
import logging
import warnings
from collections import defaultdict
from woodwork.column_schema import ColumnSchema
from woodwork.logical_types import Boolean, BooleanNullable
from featuretools import primitives
from featuretools.entityset.entityset import LTI_COLUMN_NAME
from featureto... | |
<gh_stars>0
import tkinter as tk
from tkinter import messagebox
import re
import math
import os
from time import strftime, localtime
import codecs # log output for windows `
# ------------------ log function ---------------------
def printLog(strLogMsg):
print(strLogMsg)
fileLog = codecs.open("./cal_v3.log", 'a', "u... | |
= value
value_columns = reference_curve.options["value_column_names"]
uncertainty_columns = reference_curve.options["uncertainty_column_names"]
number_plots = len(value_columns)
number_columns = int(plot_options["plots_per_column"])
number_rows = int(round(float(number_plots) / float(number_columns)))
fig, refer... | |
#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#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 ... | |
'exclude_expired' in params:
query_params.append(('exclude_expired', params['exclude_expired'])) # noqa: E501
if 'limit' in params:
query_params.append(('_limit', params['limit'])) # noqa: E501
if 'offset' in params:
query_params.append(('_offset', params['offset'])) # noqa: E501
if 'sort' in params:
query_param... | |
revision_history_limit: Optional[int]
paused: Optional[bool]
progress_deadline_seconds: Optional[int]
restart_at: Optional[datetime.datetime]
strategy: Any
class RolloutBlueGreenStatus(RolloutBaseModel):
active_selector: Optional[str]
post_promotion_analysis_run: Optional[str]
post_promotion_analysis_run_status... | |
<filename>DeepAnalogs/utils.py
# "`-''-/").___..--''"`-._
# (`6_ 6 ) `-. ( ).`-.__.`) WE ARE ...
# (_Y_.)' ._ ) `._ `. ``-..-' PENN STATE!
# _ ..`--'_..-_/ /--'_.' ,'
# (il),-'' (li),' ((!.-'
#
# Author: <NAME> <<EMAIL>>
# Geoinformatics and Earth Observation Laboratory (http://geolab.psu.edu)
# Department of Geography... | |
<reponame>theunissenlab/sounsig<gh_stars>10-100
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
from sklearn.ensemble impor... | |
val)
pass #print("00000000")
pass #print("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",full)
pass #print("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
if self._showLoading == True :#or True:
print(f" ::: Loading History ::: {id}", end="\r\r\r\r")
print()
try:
while(manager._fin is False and time.time()-t0 < timeOut):... | |
<gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... | |
of items, '+' is faster than ''.join(...)
value = (self.protocol + '://' +
self.get_header('host') +
self.app +
self.path)
if self.query_string:
value = value + '?' + self.query_string
return value
url = uri
"""Alias for uri"""
@property
def relative_uri(self):
"""The path + query string portion of the ... | |
o'er with white;",
"When lofty trees I see barren of leaves,",
"Which erst from heat did canopy the herd,",
"And summer's green all girded up in sheaves,",
"Borne on the bier with white and bristly beard,",
"Then of thy beauty do I question make,",
"That thou among the wastes of time must go,",
"Since swe... | |
<gh_stars>1-10
#!/usr/bin/env python
#################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). #
# You may not use this file except in compliance with the... | |
# Copyright 2018 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
half_w
da = 0.5 * abs(a1 - a0)
d = (
self.bend_radius[kk]
* numpy.tan(da)
/ (v0[0] ** 2 + v0[1] ** 2) ** 0.5
)
np = max(
2,
1
+ int(
da / numpy.arccos(1 - self.tolerance / r)
+ 0.5
),
)
angles = numpy.linspace(a0, a1, np)
points = (
r
* numpy.vstack(
(numpy.cos(angles), numpy.sin(angles))
).T
)
ar... | |
<gh_stars>0
import os
from psaw import PushshiftAPI
import datetime as dt
import praw
from praw.models import MoreComments
import time
import numpy as np
import random
import csv
import pandas as pd
import codecs
import re
import sys
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import json
f... | |
<filename>src/textacy/extract/basics.py<gh_stars>1000+
"""
Basics
------
:mod:`textacy.extract.basics`: Extract basic components from a document or sentence
via spaCy, with bells and whistles for filtering the results.
"""
from __future__ import annotations
from functools import partial
from typing import Collection,... | |
bin_centers[0] - fwhm / 2.) and (x < bin_centers[-1] + fwhm / 2.):
i = np.argmin(np.abs(bin_centers - x))
bflx[i] += z
bnrm[i] += 1
bflx /= bnrm
# Pad the binned flux by 5% on each side to get rid of edge effects
pad = int(0.05 * len(bin_centers))
bin_centers = bin_centers[pad:-pad]
bflx = bflx[pad:-pad]
#... | |
######################################
# DO NOT USE ON WALLABY #
# USE THE ONE IN /usr/lib/wallaby.py #
# INSTEAD #
######################################
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.2
#
# Do not make changes to this file unless you know what you are doing--modi... | |
classification in [
# First we try rerunning every pass we've previously seen succeed.
PassClassification.DUBIOUS,
# If that didn't work, we pull in some new candidate passes.
PassClassification.CANDIDATE,
# If that still didn't work, we now pull out all the stops and
# bring in the desperation passes. These are ... | |
fetched will contain the updated state, such as percent complete, the current state of the request, and any failures.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_functi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.