input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>notebooks/final/_04-tb-testing-your-causal-graph.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light,md
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Test... | |
1003
# 车辆 四轮车 燃油四轮车 1004
# 车辆 两轮车 1011
# 车辆 两轮车 两轮单车 1012
# 车辆 两轮车 两轮助力车 1013
#
# 换电柜 2000
# 换电柜 二轮车换电柜 2001
#
# 电池 3000
# 电池 磷酸铁电池 3001
# 电池 三元锂电池 3002
#
# 回收设备 4000
#
# 垃圾分类回收 4001
#
# 洗车机 5000
#
# 通用计算设备 6000
# 移动设备 6001
# 智能手机 6002
# 工业掌机 6003
# 平板电脑 6004
# 云设备 6011
# 云计算服务器 6... | |
import json
import os
import sys
import docopt
import pkg_resources
import six
from six.moves import urllib
import dcoscli
from dcos import (cmds, config, emitting, http,
metronome, options, packagemanager, util)
from dcos.cosmos import get_cosmos_url
from dcos.errors import DCOSException, DCOSHTTPException
from dco... | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/Julian/Desktop/MathApp.ui'
#
# Created by: PyQt5 UI code generator 5.12.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWind... | |
address
:param deadline: uint32
"""
return self.C_.call_getter('certTransferOwner', {'target': target, 'new_owner': new_owner, 'deadline': deadline}, key=ts4_key, expect_ec=ts4_expect_ec, decode=ts4_decode, decoder=ts4_decoder)
def R_certTransferOwner(self, target, new_owner, deadline, ts4_expect_ec=0):
"""
Wrap... | |
<filename>eeris_nilm/nilm.py
"""
Copyright 2020 <NAME>
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 ... | |
This mixin is used for any association class for which the subject (source node) plays the role of a 'model', in
that it recapitulates some features of the disease in a way that is useful for studying the disease outside a
patient carrying the disease
"""
_inherited_slots: ClassVar[List[str]] = []
class_class_uri... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 11:09:03 2020
@author: <NAME>
"""
import sys, os
import numpy as np
from math import ceil
import xarray as xr
import multiprocessing as mpi
import time
from joblib import Parallel, delayed
from tqdm import tqdm
import scipy.stats as st
from scipy... | |
self.assertTrue('config_id1' and 'Substrate Polkadot' in args)
self.assertEqual(updated_configs_chain['config_id1']['id'],
args[0].repo_id)
self.assertEqual(updated_configs_chain['config_id1']['parent_id'],
args[0].parent_id)
self.assertEqual(
updated_configs_chain['config_id1']['repo_name'] + '/',
args[0].repo_... | |
<filename>modules/s3db/deploy.py
# -*- coding: utf-8 -*-
""" Sahana Eden Deployments Model
@copyright: 2011-2019 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal... | |
'''
This File Provides the Funktions for the Montecarlo simulation
To start use MLG.Start
'''
from MLG import path,default_table, message_folder, Version,Subversion
from MLG.Simulation import RawData
from MLG.Simulation import RealData
from MLG.Modeling import fitting_micro , fitting_motion
from MLG.Math import perce... | |
<gh_stars>0
import argparse
import time
import datetime
import os
import logging
import pickle
import csv
from collections import deque
from baselines.ddpg.ddpg import DDPG
import baselines.common.tf_util as U
from baselines import logger, bench
from baselines.common.misc_util import (
set_global_seeds,
boolean_fl... | |
# modified from: https://github.com/NVlabs/latentfusion/blob/master/latentfusion/three/quaternion.py
import math
import torch
from torch.nn import functional as F
@torch.jit.script
def acos_safe(t, eps: float = 1e-7):
return torch.acos(torch.clamp(t, min=-1.0 + eps, max=1.0 - eps))
@torch.jit.script
def ensure_ba... | |
'metric-style',
_yang_ns._namespaces['Cisco-IOS-XR-clns-isis-cfg'],
'ydk.models.cisco_ios_xr.Cisco_IOS_XR_clns_isis_cfg'
),
},
'Isis.Instances.Instance.Afs.Af.AfData.MetricStyles' : {
'meta_info' : _MetaInfoClass('Isis.Instances.Instance.Afs.Af.AfData.MetricStyles',
False,
[
_MetaInfoClassMember('metric-style... | |
from __future__ import print_function
import os
import re
import sys
import ast
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from textwrap import dedent
from .. import lib
from ..configuration import I... | |
+ 35*m.x82 + 50*m.x83 + 20*m.x84 + 30*m.x85 + 25*m.x86 + 50*m.x87 + 15*m.x88 + 20*m.x89
+ 30*m.x104 + 40*m.x105 - m.x114 - m.x115 + 80*m.x130 + 90*m.x131 + 285*m.x132 + 390*m.x133
+ 290*m.x134 + 405*m.x135 + 280*m.x136 + 400*m.x137 + 290*m.x138 + 300*m.x139 + 350*m.x140
+ 250*m.x141 - 5*m.b458 - 4*m.b459 - 8*m.b460 ... | |
"""
Module to handle the reflections between game objects.
Methods
-------
reflect_from_platform(ball: Ball, platform: Platform) -> bool:
Checks if ball collides with platform and reflects from if True.
Returns True on reflect
reflect_from_game_objects(
ball: Ball, game_objects: List[GameObject]
) -> List[GameObje... | |
<reponame>rcsb/py-rcsb_app_file
##
# File: IoUtils.py
# Author: jdw
# Date: 30-Aug-2021
# Version: 0.001
#
# Updates:
##
"""
Collected I/O utilities.
"""
__docformat__ = "google en"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "Apache 2.0"
import asyncio
import functools
import gzip
import hashlib
import... | |
# Only one of 'scales' and 'sizes' can be specified.
# https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Resize-11
assert len(operation.config.input_quantization_config) in {3, 4}, f'Resize Operation {operation.name} should have 3 - 4 inputs, '\
f'while {len(operation.config.input_quantization_config)} was ... | |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from typing import List
from ReinLife.World.entities import Agent
from ReinLife.Models.utils import BasicBrain
class Tracker:
""" Used for tracking results of an experiment
Variables tracked:
* Avg Population Size
* Avg Population Age
* Avg Po... | |
from json import load
from os.path import dirname, exists, join
from pymongo import MongoClient # https://github.com/mongodb/mongo-python-driver
from bson import ObjectId
from traceback import format_exc
from common.loggable_api import Loggable
class DatabaseApi(Loggable):
"""
Reveals API for database, i.e. MongoDB... | |
import datetime
from .exceptions import PlayerNotFound
from .Classes import *
from .utils import Requests
class PlayerInfo:
def __init__(self, request: Requests, playerID: int):
"""
Represents a ROBLOX User.
**Parameter**
-------------
playerID : int
player ID
request : roblox_py.Requests
Requests Class ... | |
else:
iprot.skip(ftype)
elif fid == 15:
if ftype == TType.LIST:
self.annotations = []
(_etype10, _size7) = iprot.readListBegin()
for _i11 in range(_size7):
_elem12 = TAnnotation()
_elem12.read(iprot)
self.annotations.append(_elem12)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 16:
if ftype == T... | |
# Copyright (c) 2012 <NAME>
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# =======================================================================
"""make plant loop snipp... | |
<filename>desdeo_problem/problem/Objective.py
"""Defines Objective classes to be used in Problems
"""
from abc import ABC, abstractmethod
from os import path
from typing import Callable, Dict, List, NamedTuple, Tuple, Union
import numpy as np
import pandas as pd
from desdeo_problem.surrogatemodels.SurrogateModels i... | |
import os
import logging
import json
import asyncio
import zlib
import base64
from collections import OrderedDict
from typing import Tuple, Dict, List, Union
from aioupnp.fault import UPnPError
from aioupnp.gateway import Gateway
from aioupnp.util import get_gateway_and_lan_addresses
from aioupnp.protocols.ssdp import ... | |
Int(0, iotype='in', desc='Number of RERUN namelists to be created')
npcons = Array(iotype='in', dtype=numpy_int64, desc='Number of PCONIN ' +
'namelists to be created with each RERUN namelist')
# Variable Trees
input = VarTree(FlopsWrapper_input(), iotype='in')
output = VarTree(FlopsWrapper_output(), iotype='out'... | |
tf.contrib.seq2seq.dynamic_decode(inference_decoder,
impute_finished=True,
maximum_iterations=max_target_sequence_length)
return inference_decoder_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_infer(decoding_layer_infer)
# ### Build the Decoding Layer
# Implem... | |
<reponame>Pantalaymon/coreferee<gh_stars>0
from typing import List, Tuple, Dict
import importlib
import sys
from os import sep
from abc import ABC, abstractmethod
from threading import Lock
import pkg_resources
from spacy.language import Language
from spacy.tokens import Token, Doc
from .data_model import ChainHolder, ... | |
<filename>Control.py<gh_stars>10-100
from UI.UI import Ui_MainWindow
from UI.reminder import Ui_reminder
from UI.property import Ui_Property
from UI.information import Ui_Information
from UI.MessageBox import MessageBox
from UI.inquire import Ui_Inquire
from UI.wrong import Ui_Wrong
from UI.final import Ui_final_2
from... | |
import logging
import time
from exceptions import ObjectError
from block import Block
from _namespace import customize_blockreplica
LOG = logging.getLogger(__name__)
class BlockReplica(object):
"""Block placement at a site. Holds an attribute 'group' which can be None.
BlockReplica size can be different from that ... | |
#!/usr/bin/env python
"""Backup Now and Copy for python"""
# version 2022.03.11
### usage: ./backupNow.py -v mycluster -u admin -j 'Generic NAS' [-r mycluster2] [-a S3] [-kr 5] [-ka 10] [-e] [-w] [-t kLog]
### import pyhesity wrapper module
from pyhesity import *
from time import sleep
from datetime import datetime
... | |
0xbf24, 0xbd97, 0x3f35,
0xbf35, 0xbe23, 0xbef6, 0xbf3d, 0x3efd, 0xbd15, 0xbe84, 0x3f0c, 0x3f30, 0x3f27,
0xbec4, 0xbe3e, 0x3d44, 0xbf2a, 0x3f0f, 0xbe9a, 0x3f37, 0x3f04, 0xbf14, 0x3e8b,
0x3eb3, 0xbe93, 0x3dcd, 0xbfbd, 0x3f0c, 0x3c13, 0x3e8b, 0xbe5b, 0x3e6e, 0x3ef3,
0x3f0f, 0xbe88, 0xbe61, 0xbefa, 0xbdb8, 0xbf7b, 0x3f... | |
o_symBrac = obj.__symBrac
o_symText = obj.__symText
o_calBrac = obj.__calBrac
o_calText = obj.__calText
elif type(obj) == Const:
o_symBrac = obj._Const__symBrac
o_symText = obj._Const__symText
o_calBrac = obj._Const__symBrac
o_calText = obj._Const__calText
#左减需要考虑obj的括号,不用考虑self的括号
if 0 == self.__calPrior:
i... | |
# General Headers####################
import numpy as np
import copy
#####################################
# sklearn headers##################################
import xgboost as xgb
from sklearn.metrics import roc_auc_score, accuracy_score
from sklearn.model_selection import KFold
from sklearn.neighbors import NearestN... | |
mdp.getStateSpace() ) ) )
piProb = pi.selectionProbabilityMatrix( mdp.getStateSpace() )
for aind in range( len( mdp.getActionSpace() ) ):
pia = np.diag( piProb[:, aind] )
Pa = mdp.getTransitionMatrix( action=mdp.getActionSpace()[aind] )
Ppi = Ppi + np.dot( pia, Pa )
return Ppi
def stationaryDistribution( mdp, p... | |
rules,https://docs.cloud.oracle.com/Content/network/Concepts/securitylists.htm) for your virtual cloudn network. For more
information about public and
private network load balancers,
see L(How Network Load Balancing Works,https://docs.cloud.oracle.com/Content/Balance/Concepts/balanceoverview.htm#how-network-load-bal... | |
+= "1{5}" # Rt2
insn_rx += "[01]{5}" # Rn
insn_rx += "[01]{5}" # Rt
assert re.match(insn_rx, cpu.insn_bit_str)
# XXX: Support exclusive access.
base = cpu.regfile.read(mem_op.mem.base)
imm = mem_op.mem.disp
assert imm == 0
result = cpu.read_int(base, reg_op.size)
reg_op.write(result)
def _LSL_immediate(c... | |
# vim: set fileencoding=utf8 :
"""Align, register and fuse frames specified on the command line using the
DTCWT fusion algorithm.
Usage:
fuseimages [options] <frames>...
fuseimages (-h | --help)
Options:
-n, --normalise Re-normalise input frames to lie on the
interval [0,1].
-v, --verbose Increase logging verbo... | |
"""This module handles backward compatibility with the ctypes libtcodpy module.
"""
import os
import sys
import atexit
import threading
from typing import (
Any,
AnyStr,
Callable,
Hashable,
Iterable,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
import warnings
import numpy as np
from tcod.loader im... | |
'HH12'): ('ARG', '2HH1'),
('ARG', 'HH21'): ('ARG', '1HH2'),
('ARG', 'HH22'): ('ARG', '2HH2'),
('TYR', 'HB2'): ('TYR', '1HB'),
('TYR', 'HB3'): ('TYR', '2HB'),
('PHE', 'HB2'): ('PHE', '1HB'),
('PHE', 'HB3'): ('PHE', '2HB'),
('THR', 'HG21'): ('THR', '1HG2'),
('THR', 'HG22'): ('THR', '2HG2'),
('THR', 'HG23'): ('TH... | |
# usage: pytest -q solvers_test.py
import SmartDiff.solvers.element_op as el
from SmartDiff.solvers.element_op import AutoDiff as AD
import numpy as np
import pytest
class TestElemOp:
def test_power(self):
x = AD(5)
f = el.power(x, 2)
assert (f.val, f.der) == (25, 10)
x = 10
f = el.power(x, 3)
assert (f.val,... | |
0
best_end = 0
# Pycharm false positive due to for...else flow
# noinspection PyUnboundLocalVariable
return pd.Series([best_start, best_end],
index=['left_cut_end', 'right_cut_end'])
# noinspection PyUnreachableCode
def fit_percentiles(group_df: pd.DataFrame) -> pd.Series:
raise NotImplementedError
# remove ... | |
<filename>etl/parsers/etw/Microsoft_Windows_Deduplication_Change.py
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-Deduplication-Change
GUID : 1d5e499d-739c-45a6-a3e1-8cbe0a352beb
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.util... | |
is None:
return None
if 'latitude' in obj:
latitude = obj['latitude']
if latitude is not None:
latitude = round(latitude, 4)
if 'longitude' in obj:
longitude = obj['longitude']
if longitude is not None:
longitude = round(longitude, 4)
if 'depth' in obj:
depth = obj['depth']
if 'uid' in obj:
uid = obj['uid... | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.gis.geos import Point
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from django.contrib.postgres.fields import ArrayField, H... | |
<gh_stars>0
import sqlalchemy as sqla
import sys
import pandas as pd
from google.cloud import bigquery
from google.oauth2 import service_account
import re
import pymysql
from decimal import Decimal
import datetime
import time
from enum import Enum
import cx_Oracle
try:
import pyodbc
import pymssql
except ImportError... | |
"""
DIRBS DB schema migration script (v76 -> v77).
SPDX-License-Identifier: BSD-4-Clause-Clear
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) ... | |
<reponame>drastus/unicover
blocks = [
['0000', '007F', 'Basic Latin', [range(32, 127)]],
['0080', '00FF', 'Latin-1 Supplement', [range(160, 173), range(174, 256)]],
['0100', '017F', 'Latin Extended-A', [range(256, 384)]],
['0180', '024F', 'Latin Extended-B', [range(384, 592)]],
['0250', '02AF', 'IPA Extensions', [... | |
# -*- coding: utf-8 -*-
"""
Iperf command module.
+-------------------------------------------------------------------
| Deprecated module. Don't develop any more. Develop Iperf2 instead.
+-------------------------------------------------------------------
Deprecation rationale:
This command returned value requires a... | |
# -*- coding: utf-8 -*-
# reporting.py
# Copyright (c) 2014-?, <NAME>
# 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 copyright
# notic... | |
:param family:
:param mode:
:param kwargs:
:return:
"""
st.log("Configuring the BGP neighbor properties ..")
properties = kwargs
peergroup = properties.get('peergroup', None)
cli_type = get_cfg_cli_type(dut, **kwargs)
skip_error_check = kwargs.get("skip_error_check", True)
# Add validation for IPV4 / IPV6 add... | |
<gh_stars>1-10
import threading
from bitcoin.messages import *
from bitcoin.net import CAddress
from io import BytesIO as _BytesIO
import atexit
import bitcoin
import fcntl
import hashlib
import json
import os
import random
import re
import socket
import struct
import sys
import time
if os.geteuid() != 0:
sys.exit("\... | |
"""
Definition of `DjangoModelManager` class.
"""
import django.db
import django.db.models
import django.db.transaction
from django.conf import settings
try:
import django.contrib.postgres.fields
WITH_POSTGRES_SUPPORT = True
except ImportError:
WITH_POSTGRES_SUPPORT = False
import django.core.exceptions
from .. i... | |
<gh_stars>0
# -*- coding: utf-8 -*-
from builtins import int
from struct import unpack, pack
M32 = 2**32 - 1 # Mask 32-bit
S32 = 2**31 # Sign Mask 32-bit
R32 = 2**32 # Mask for logical right shift 32-bit
M64 = 2**64 - 1 # Mask 64-bit
S64 = 2**63 # Sign Mask 64-bit
R64 = 2**64 # Mask for logical right shift 64-bit
... | |
# -*- coding: utf-8 -*-
"""
Contain the implementation of the CSP algorithm. Developed for the train part of dataset IV-1-a of BCI competition.
This version (V2) implement the algorithm for data with two classes.
@author: <NAME> (Jesus)
@organization: University of Padua (Italy)
"""
#%%
import numpy as np
import mat... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI\Interface_MLP.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):... | |
def forward(self, x):
x_shape = x[0].shape
flag_seqtoseq = False
if len(x_shape) > 4:
flag_seqtoseq = True
for i in range(len(x)):
x[i] = x[i].flatten(start_dim=0, end_dim=1)
xeeg = x[0].squeeze(dim=1)
xeog = x[1].squeeze(dim=1)
xeeg = self.conv_0_eeg(xeeg)
xeog = self.conv_0_eog(xeog)
x = self.conv_1(to... | |
<gh_stars>10-100
"""ROS Bag API"""
# Author: <NAME> <<EMAIL>>
# License: MIT
import sys
import numpy as np
import cv2
import time
import os.path
import tf
import rosbag
import rospy
# from message_filters import ApproximateTimeSynchronizer
from genpy.rostime import Time
from sensor_msgs.msg import Image
from cv_bri... | |
<reponame>splumb/PuTTY
import sys
import numbers
import itertools
assert sys.version_info[:2] >= (3,0), "This is Python 3 code"
from numbertheory import *
class AffinePoint(object):
"""Base class for points on an elliptic curve."""
def __init__(self, curve, *args):
self.curve = curve
if len(args) == 0:
self.in... | |
#input all title components into metadata
if(exists == False):
M,L,N,_ = Block.snapTitle(title)
self.setMeta('vendor', M)
self.setMeta('library', L)
self.setMeta('name', N)
pass
#create a git repository if DNE
if(Git.isValidRepo(self.getPath()) == False):
self._repo = Git(self.getPath())
#perform safety mea... | |
entire lifecycle.
'id': {
'xml_name': 'id',
'xml_type': 'xs:ID'
},
# If the attribute is empty, specifies which entity (person,
# organisation or system) will edit the property - expressed by a QCode.
# If the attribute is non-empty, specifies which entity (person,
# organisation or system) has edited the prope... | |
from __future__ import division
from __future__ import print_function
from struct import unpack
import idaapi
import idautils
import idc
from PyQt5.Qt import QApplication
ACTION_CONVERT = ["lazyida:convert%d" % i for i in range(10)]
ACTION_SCANVUL = "lazyida:scanvul"
ACTION_COPYEA = "lazyida:copyea"
ACTION_GOTOCLIP =... | |
# Creates main window
root = tk.Tk()
root.title("Data Cleaning")
root.geometry("600x800")
root.resizable(width=True, height=True)
canvas = tk.Canvas(root, borderwidth=0) #, background="#ffffff")
win_root = tk.Frame(canvas) #, background="#ffffff")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yvie... | |
import logging
import os
import netCDF4 as nc
import numpy as np
import pandas as pd
import pytz
import utm
from smrf.envphys import phys
from smrf.envphys.radiation import get_hrrr_cloud
try:
from weather_forecast_retrieval import hrrr
except:
pass
class grid():
"""
Class for loading and storing the data, ei... | |
you give a
"continue" command. This allows you to break into the debugger
again by pressing "Ctrl-C". If you want Pdb not to touch the
SIGINT handler, set *nosigint* to true.
The *readrc* argument defaults to true and controls whether Pdb
will load .pdbrc files from the filesystem.
Example call to enable tracin... | |
<filename>env/Lib/site-packages/bidict/_base.py
# -*- coding: utf-8 -*-
# Copyright 2009-2020 <NAME>. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.... | |
await self.config.guild(ctx.guild).started.set(True)
redcardmodifier = await self.config.guild(ctx.guild).redcardmodifier()
team1players = list(teams[team1]["members"].keys())
team2players = list(teams[team2]["members"].keys())
logos = ["sky", "bt", "bein", "bbc"]
yellowcards = []
logo = random.choice(logos)
mot... | |
path.
instance = cls.__new__(cls)
super(cls, instance).__setattr__("_pb", pb)
return instance
def serialize(cls, instance) -> bytes:
"""Return the serialized proto.
Args:
instance: An instance of this message type, or something
compatible (accepted by the type's constructor).
Returns:
bytes: The serialized... | |
interval.GenericInterval('descending fifth')
>>> bInterval = interval.ChromaticInterval(-8)
>>> cInterval = interval.intervalFromGenericAndChromatic(aInterval, bInterval)
>>> cInterval
<music21.interval.Interval A-5>
>>> cInterval.name
'A5'
>>> cInterval.directedName
'A-5'
>>> cInterval.directedNiceName
'Des... | |
<reponame>defeo/sage<gh_stars>0
r"""
Free module bases
The class :class:`FreeModuleBasis` implements bases on a free module `M` of
finite rank over a commutative ring,
while the class :class:`FreeModuleCoBasis` implements the dual bases (i.e.
bases of the dual module `M^*`).
AUTHORS:
- <NAME>, <NAME> (2014-2015): in... | |
score:
quality = q
score = s
return quality
def quality_from_buffer_placeholder(self):
return self.quality_from_buffer(get_buffer_level() + self.placeholder)
def min_buffer_for_quality(self, quality):
global manifest
bitrate = manifest.bitrates[quality]
utility = self.utilities[quality]
level = 0
for q i... | |
<filename>nsidc_upload/dems/oib_parallel_uploader.py
import os, sys, logging, datetime, multiprocessing, icebridge_common, shutil
import threading, time
import flight_list # Contains AN_FLIGHTS and GR_FLIGHTS
#===============================================================================
# Constants
COMPLETED_DAT... | |
= name
# if mod_name is not None:
# OuterMocker.__module__ = kwargs['module']
str_func = attributes.pop('__str__', None)
repr_func = attributes.pop('__repr__', None)
if str_func is not None: c.__str__ = str_func
if repr_func is not None: c.__repr__ = repr_func
return c(modules=modules, attributes=attributes, *... | |
<gh_stars>10-100
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 for python
#
# written in python3, (c) 2019-202... | |
PRINTER NAME COMBOS
#
# ***********************************************************************************
def updatePrinterList(self):
if self.cur_device is not None and \
self.cur_device.supported:
printers = cups.getPrinters()
self.cur_device.cups_printers = []
for p in printers:
if p.device_uri == self... | |
# coding:utf8
from django.db import models
from django.template.defaultfilters import default
from import_export import fields
from import_export import resources
# Create your models here.
def get_uploadto_path(model, filename):
return 'media/%s' % (filename)
SEX_TYPE_LIST = (
('女', '女'),
('男', '男'),
)
PRODUCT... | |
bmpsize))
## BMP header reserved fields
icooutput.write('\x00\x00\x00\x00')
## BMP header offset of pixel array
## first there is the BMP file header,
## which is 14 bytes, then the DIB
## header, in total 54 bytes
pixelarrayoffset = 54
## Then there is an optional color table
bitspe... | |
send back and log the request.
api_request = APIRequest(
authentication_type='NO_AUTH',
type=request.method,
url=request.get_full_path(),
status='401 ERR',
ip_address=get_client_ip(request),
source=request.META['HTTP_USER_AGENT'],
response_to_user=response,
)
api_request.save()
return HttpResponse(response... | |
#!/usr/bin/env python
"""
Code for linting modules in the nf-core/modules repository and
in nf-core pipelines
Command:
nf-core modules lint
"""
from __future__ import print_function
import logging
from nf_core.modules.modules_command import ModuleCommand
import operator
import os
import questionary
import re
import r... | |
<reponame>ImperialCollegeLondon/pyWINDOW<filename>pywindow/trajectory.py
"""
Module intended for the analysis of molecular dynamics trajectories.
The trajectory file (DL_POLY_C:HISTORY, PDB or XYZ) should be loaded with
the one of the corresponding classes (DLPOLY, PDB or XYZ, respectively).
Example
-------
In this e... | |
# Copyright 2019 Kyoto University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""CTC decoder."""
from collections import OrderedDict
from distutils.version import LooseVersion
from itertools import groupby
import logging
import numpy as np
import random
import torch
import torch.nn as nn
from ... | |
<filename>yaappu/utils.py
import grammar
from itertools import islice
from operator import itemgetter
from collections import Counter
from enum import IntEnum
_TREAT_AAYDHAM_AS_KURIL = False
_TREAT_KUTRIYALIGARAM_AS_OTRU = False
AYDHAM = ('ஃ')
UYIRGAL = ("அ","ஆ","இ","ஈ","உ","ஊ","எ","ஏ","ஐ","ஒ","ஓ","ஔ")
MEYGAL... | |
# -*- coding: UTF-8 -*-
# This file is part of the orbot package (https://github.com/officinerobotiche/orbot or http://www.officinerobotiche.it).
# Copyright (C) 2020, <NAME> <<EMAIL>>
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided tha... | |
calc_od=[],
pre_process=True, prefit_shift=0.0, interp_method='cubic',
fit_window=None):
"""Fit the supplied spectrum.
Parameters
----------
spectrum : tuple
The measured spectrum in the form [wavelengths, intensities]
update_params : bool, optional
Flag whether to update the initial fit parameters upon a suc... | |
# Music World Sprite Ripper
# Version 1.0
# By Buu342
import os
import sys
import math
import numpy as np
from PIL import Image as im
from pathlib import Path
########################
# Globals
########################
# Start and end offsets in the uncompressed.pxo where sprites are located
# Values obtained by es... | |
= y + self.margin
def drawLegend(self, elements, unique=False):
# elements is [ (name,color,rightSide), (name,color,rightSide), ... ]
self.encodeHeader('legend')
if unique:
# remove duplicate names
namesSeen = []
newElements = []
for e in elements:
if e[0] not in namesSeen:
namesSeen.append(e[0])
newElemen... | |
result = await return_json_senpai(LS_INFO_QUERY, vars_, auth=auth, user=user)
data = result["data"]["Character"]["media"]["nodes"]
if req == "ANI":
out = "ANIMES:\n\n"
out_ = []
for ani in data:
k = ani["title"]["english"] or ani["title"]["romaji"]
kk = ani["type"]
if kk == "ANIME":
out_.append(f"• __... | |
<filename>tests/unit/test_loader.py
import json
import os
import pytest
import yaml
from path import Path
from formica.loader import Loader
from datetime import datetime, timedelta, timezone
@pytest.fixture()
def load():
return Loader()
def write_and_test(example, load, tmpdir):
with Path(tmpdir):
with open('t... | |
<gh_stars>0
#!/usr/bin/env python3
#------------------------------
# VERSION: v3.9 |
#------------------------------
# CPSC 386 Final Project
# Game: Stinky Shoe Clicker!
# Click the sneaker and generate points! Upgrade your clicker and watch
# out for mudslides. A filthy sneaker is a stinky sneaker, so clean it
# u... | |
+ 2567649375 * uk_78
+ 901530225 * uk_79
+ 79 * uk_8
+ 316537279 * uk_80
+ 166375 * uk_81
+ 75625 * uk_82
+ 238975 * uk_83
+ 24200 * uk_84
+ 644325 * uk_85
+ 680625 * uk_86
+ 238975 * uk_87
+ 34375 * uk_88
+ 108625 * uk_89
+ 2572416961 * uk_9
+ 11000 * uk_90
+ 292875 * uk_91
+ 309375 * uk_92
+ 108625 *... | |
val_dataset, sampler=val_sampler,
batch_size=args.batch_size, shuffle=(val_sampler is None),
# different gpu forward is different, thus it's necessary
num_workers=args.workers, pin_memory=True)
elif args.dataset == "Place205":
from data_processing.Place205_Dataset import Places205
normalize = transforms.Normali... | |
""" This module handles everything related to log parsing """
import re # For parsing the log file (regular expressions)
import os # For working with files on the operating system
import logging # For logging
from game_objects.item import Item
from game_objects.floor import Floor, Curse
from game_objects.state import T... | |
<filename>apps/logs/views.py
from collections import Counter
from functools import reduce
from pprint import pprint
from time import monotonic
from core.exceptions import BadRequestException
from core.filters import PkMultiValueFilterBackend
from core.logic.dates import date_filter_from_params, parse_month
from core.l... | |
into project
for rc_file in p.rp_render_controllers:
for rc_obj in rc_file:
new_rc = project_rcs.add()
# new_rc.name: String
new_rc.name = rc_obj.json.parent_key
# new_rc.geometry_molang: String
new_rc.geometry_molang = rc_obj.geometry
# new_rc.texture_molang: String
if len(rc_obj.textures) > 0: # Currently on... | |
return ( None )
if 31 - 31: I11i . i11iIiiIii . OoO0O00 * Oo0Ooo % Ii1I . o0oOOo0O0Ooo
self . nonce , self . key_id , self . alg_id , self . auth_len = struct . unpack ( oOo0ooO0O0oo , packet [ : OO00OO ] )
if 92 - 92: OoooooooOO / O0 * i1IIi + iIii1I11I1II1
self . nonce_key = lisp_hex_string ( self . nonce )
self... | |
# -*- coding: utf-8 -*-
'''
Manage VMware vCenter servers and ESXi hosts.
.. versionadded:: 2015.8.4
:codeauthor: :email:`<NAME> <<EMAIL>>`
Dependencies
============
- pyVmomi Python Module
- ESXCLI
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version ... | |
from kucoin.base_request.base_request import KucoinBaseRestApi
class TradeData(KucoinBaseRestApi):
def create_limit_order(self, symbol, side, size, price, clientOid='', **kwargs):
"""
https://docs.kucoin.com/#place-a-new-order
:param symbol: a valid trading symbol code (Mandatory)
:type: str
:param side: place... | |
<gh_stars>0
"""
buzzword explorer: callbacks
"""
import pandas as pd
from buzz.exceptions import DataTypeError
from dash import no_update
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from explore.models import Corpus
from django.conf import settings
from .chart import ... | |
if self.dimensionsMatch(other):
self.px = self.px * other.getPixelMap()
def divideImage(self, other):
""" Multiply pixel values by another image. """
if self.dimensionsMatch(other):
self.px = self.px / other.getPixelMap()
def square(self):
self.px *= self.px
def sqrt(self):
self.px = numpy.sqrt(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.