text stringlengths 957 885k |
|---|
<reponame>AllanDaemon/vscode-python<filename>pythonFiles/jedi/evaluate/imports.py
"""
:mod:`jedi.evaluate.imports` is here to resolve import statements and return
the modules/classes/functions/whatever, which they stand for. However there's
not any actual importing done. This module is about finding modules in the
file... |
<reponame>musiclvme/distant_speech_recognition
#!/usr/bin/python
"""
Test subband acoustic echo cancellation on the single channel data.
.. moduleauthor:: <NAME>, <NAME> <<EMAIL>>
"""
import argparse, json
import os.path
import pickle
import wave
import sys
import numpy
from btk20.common import *
from btk20.stream im... |
<reponame>gaceladri/draft
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import functools
import collections
from code.util import cast_like, dropout_with_broadcast_dims, should_generate_summaries, shape_list
from code.util import _... |
<gh_stars>10-100
import json
import click
import requests
import time
class BadRequestException(Exception):
def __init__(self, message, rv):
super(BadRequestException, self).__init__(message)
self.rv = rv
def api_get(domain, api_key, path):
url = "https://{}/api/v2/{}".format(domain, path)
... |
# TODO: Add folder_to_lib functionality
# Friday, February 5, 2020
"""
**folder_to_lib.py**
This module will be where the functions for taking path/to/folder outputs from cpgfunction are combined
into a library.json file
"""
# import os
# from . import platform_specific
# from . import fileio
# from . import hand... |
<reponame>yanhuaijun/test01
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
# Register your models here.
class UserType(models.Model):
name = models.CharField(max_length=32)
class wxuser(models.Model): #微信用户表
unionid = models.CharField(max_len... |
<reponame>FrederichRiver/neutrino<gh_stars>1-10
#!/usr/bin/python3
# from statsmodels.tsa.arima_model import ARIMA
import datetime
import pandas as pd
import numpy as np
import requests
import time
import random
from env import global_header
from libmysql8 import mysqlHeader, mysqlBase
from libstock import wavelet_nr, ... |
# Generated by Django 3.2 on 2021-04-20 16:44
from django.db import migrations, models
import django.db.models.deletion
import playlists.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('videos', '0001_initial'),
('categories', '0001_initial'),
]
opera... |
# -*- coding: utf-8 -*-
# Copyright 2017, Digital Reasoning
#
# 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 applica... |
from django.contrib import admin
from rolepermissions.roles import assign_role
from .models import (BtcDepositAddress, Category, Profile, Listing,
BtcAddressChangeHistory, Transaction, BalanceChange,
Fee, AffiliateCommision, Withdrawal, Message, Feedback, BtcPrice)
def make_... |
<gh_stars>0
"""
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=... |
<filename>NT_UDA/demo_syn_dnn.py
# -*- coding: utf-8 -*-
# A Survey on Negative Transfer
# https://github.com/chamwen/NT-Benchmark
import numpy as np
import argparse
import random
import os
import torch as tr
import torch.nn as nn
import torch.optim as optim
from utils import network, loss, utils
from utils.dataloader ... |
# -*- coding: utf-8 -*-
import gc
import json
import structlog
from django.db import migrations
log = structlog.get_logger(__name__)
def chunks(queryset, chunksize=1000):
pk = 0
queryset = queryset.order_by('pk')
last_instance = queryset.last()
if last_instance is not None:
last_pk = last_i... |
<reponame>goldmanm/atmospheric-sar-comparison
#!/usr/bin/env python
# encoding: utf-8
name = "Atkinson2007"
longDesc = u"""
The reaction site *3 needs a lone pair in order to react. It cannot be 2S or 4S.
"""
entry(
label = "parent",
group =
"""
1 *3 R u1
""",
data = None
)
entry(
label = "methyl",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Rimco'
# System imports
import datetime
import logging
import random
import time
import errno
from threading import Lock
BRUTEFORCE_LOCK = Lock()
def del_rw(action, name, exc):
import os
import stat
if os.path.exists(name):
os.chmod(na... |
"""
dj-stripe Account Tests.
"""
from copy import deepcopy
from unittest.mock import patch
import pytest
from django.test.testcases import TestCase
from djstripe.models import Account
from djstripe.settings import STRIPE_SECRET_KEY
from . import (
FAKE_ACCOUNT,
FAKE_FILEUPLOAD_ICON,
FAKE_FILEUPLOAD_LOGO,... |
<reponame>pytaunay/multiwavelength-pyrometry
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation... |
<reponame>jhbez/focus
# -*- coding: utf-8 -*-
# Copyright 2017 ProjectV Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... |
<reponame>wycivil08/blendocv
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.... |
<reponame>wuchen-huawei/huaweicloud-sdk-python-v3<filename>huaweicloud-sdk-oms/huaweicloudsdkoms/v2/model/smn_info.py<gh_stars>1-10
# coding: utf-8
import pprint
import re
import six
class SmnInfo:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the... |
"""Test MIROC-ESM fixes."""
import unittest
from cf_units import Unit
from iris.coords import DimCoord
from iris.cube import Cube
from iris.exceptions import CoordinateNotFoundError
from esmvalcore.cmor._fixes.cmip5.miroc_esm import AllVars, Cl, Co2, Tro3
from esmvalcore.cmor._fixes.common import ClFixHybridPressureC... |
import rospy
import numpy as np
from gym import spaces
from openai_ros.robot_envs import modrob_env
from gym.envs.registration import register
from geometry_msgs.msg import Point
from openai_ros.task_envs.task_commons import LoadYamlFileParamsTest
from openai_ros.openai_ros_common import ROSLauncher
import os
class Mo... |
<gh_stars>10-100
import numpy , pandas
from sklearn import model_selection
from sklearn import neural_network
#--------------------------------------------------
''' Representation '''
data = pandas.read_csv('sonar.csv')
X = data[data.columns[0:60]]
Y = data[data.columns[60]]
X , Y = sklearn.utils.shuffle(X , Y , rando... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse,os,sys,re
import multiprocessing as mp
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Bo... |
<reponame>xyzza/m3-core
# coding: utf-8
u"""Паки и экшены для работы со справочниками."""
from logging import getLogger
from django.conf import settings
from m3.actions import (
ActionPack, Action, PreJsonResult, OperationResult, ACD
)
from m3_django_compat import atomic
from m3_ext.ui.windows.complex import ExtDi... |
import array as arr
import numpy as np
from operator import add
from tabulate import tabulate
import os.path
print("Enter your date of birth: \n")
day = input("Day: ")
month = input("Month: ")
year = input("Year: ")
print("Enter your name \n")
name = input()
save_path = ""
# Set the path to save the t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-11-05 11:30:01
# @Author : <NAME> (<EMAIL>)
# @Link : http://cs.ucsb.edu/~bolunwang
import os
import time
import numpy as np
import random
import tensorflow
from tensorflow import set_random_seed
random.seed(123)
np.random.seed(123)
set_random_seed(1... |
<filename>train.py
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
"""
Training part of the Deep QA model
"""
from __future__ import print_function
from __future__ import division
__copyright__ = "Copyright (c) 2017 Xuming Lin. All Rights Reserved"
__author__ = "<NAME>, <NAME><<EMAIL>>"
__date__ = "201... |
<reponame>matejklemen/slovene-coreference-resolution
import json
from collections import Counter
import logging
import os
from typing import List, Optional, Mapping
from sklearn.model_selection import train_test_split
PAD_TOKEN, PAD_ID = "<PAD>", 0
BOS_TOKEN, BOS_ID = "<BOS>", 1
EOS_TOKEN, EOS_ID = "<EOS>", 2
UNK_TO... |
<filename>tests/test_postprocessing.py
import numpy as np
import pytest
from component_vis import factor_tools, postprocessing
def test_normalise_cp_tensor_normalises(rng):
A = rng.standard_normal((10, 3))
B = rng.standard_normal((20, 3))
C = rng.standard_normal((30, 3))
D = rng.standard_normal((40, 3... |
<filename>storyboard/notifications/subscriber.py<gh_stars>0
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.apach... |
<filename>clictest/notifier.py
# Copyright 2011, OpenStack Foundation
# Copyright 2012, Red Hat, Inc.
# Copyright 2013 IBM Corp.
#
# 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
#
# ... |
import argparse
import csv
import os
from typing import Iterable
import molanet.data.feature_extraction.data_analysis as data
from molanet.data.database import DatabaseConnection
from molanet.data.entities import MoleSample
def compute_features(sample: MoleSample):
hair = data.contains_hair(sample.image)
pla... |
import json
import random
from copy import deepcopy
from datetime import datetime
from flask import Markup
from flask import Response, current_app, flash, redirect, url_for
from flask_admin.actions import action
from quokka.utils.text import slugify
class PublishAction(object):
@action(
'toggle_publish... |
'''
@description 2019/09/09 23:44
'''
# 列表的常用方法:
# 1.append:在列表末尾添加元素
# JavaScript
'''
fruits = ['苹果']
fruits.push('香蕉')
'''
fruits = ['苹果']
fruits.append('香蕉')
print(fruits) # ['苹果', '香蕉']
print('='*20)
# 2.count: 统计某个元素在列表中出现的次数
word_lsit = ['to', 'be', 'or', 'not', 'to', 'be']
word_count = word_lsit.count('be')... |
<reponame>Underscore-tZ/mkw-sp
#!/usr/bin/env python3
import os, sys
from vendor.ninja_syntax import Writer
try:
import json5
del json5
except ModuleNotFoundError:
raise SystemExit("Error: pyjson5 not found. Please install it with `python -m pip install json5`")
n = Writer(open('build.ninja', 'w'))
n.v... |
import os
import codecs
import random
from docopt import docopt
from collections import defaultdict
def main():
"""
Sample from the top K of each day and create batch instances.
"""
args = docopt("""Sample from the top K of each day and create batch instances.
Usage: sample_for_second_annot... |
<filename>src/cython/move.py
#<PyxReplace>#
from collections import namedtuple
from utils.fake_cython import cython
Board = namedtuple("Board", "none")
from constants import (
# Directions
N, S, E, W,
EMPTY,
# Board
A1, A7, H1, H7,
# Pieces
PAWN, ROOK, QUEEN, KING, PIECE_EMPTY,
# Colors... |
<reponame>JI411/fuzzy-doc-search
"""
Class for OCR scanned_pdf
"""
# pylint: disable=line-too-long
import tempfile
from pathlib import Path
from multiprocessing import Pool
from typing import Dict, List, Any
import datetime
import cv2
import numpy as np
from PIL import Image
import pytesseract
import fitz
import pdf... |
import sys
from django.contrib.admin.forms import forms
from django.conf import settings
from django.apps import apps
from muddery.worlddata import forms_base
class GameSettingsForm(forms_base.GameSettingsForm):
pass
class ClassCategoriesForm(forms_base.ClassCategoriesForm):
pass
class TypeclassesForm(forms... |
<gh_stars>1-10
#!/usr/local/bin/python2 -tt
from scapy.all import *
import struct
MESSAGETYPEOFFSETUDP = 17
MESSAGETYPEOFFSETTCP = 21
DEBUG = True
TGS_REP = chr(13)
def findkerbpayloads(packets, verbose=False):
kploads = []
i = 1
unfinished = {}
for p in packets:
# UDP
if p.haslayer(UDP) and p.sport == 88 a... |
# Copyright 2017 Uber Technologies, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from github_webhook import Webhook
from flask import Flask, make_response, request
from json import JSONDecodeError
from protected_repo import ProtectedRepository
from threading import Thread
from mail import Email, FakeEmail
import json
import os
basepath = os.path.dirname(__file__)
CONFIG_FILE = "config.json"
def l... |
#!/usr/bin/env python3
#
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import inspect
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
... |
from secml.ml.features.tests import CPreProcessTestCases
from sklearn.preprocessing import Normalizer
from secml.array import CArray
from secml.ml.features.normalization import CNormalizerUnitNorm
from secml.optim.function import CFunction
class TestCNormalizerUnitNorm(CPreProcessTestCases):
"""Unittest for CNo... |
"""
Oscillators.
"""
import souffle.datatypes as dtt
##### Default constants #####
# Brusselator, unstable regime
BRUSS_A = 1.0
BRUSS_B = 3.0
# Lotka-Volterra
LOTKA_ALPHA = 1.5
LOTKA_BETA = 1.0
LOTKA_GAMMA = 2.0
LOTKA_DELTA = 1.0
# van der Pol oscillator
VANDERPOL_MU = 5.0
VANDERPOL_OMEGA = 1.0
######################... |
<reponame>MaxTurchin/pycopy-lib
"""
Define names for built-in types that aren't directly accessible as a builtin.
"""
import sys
# Iterators in Python aren't a matter of type but of protocol. A large
# and changing number of builtin types implement *some* flavor of
# iterator. Don't check the type! Use hasattr to c... |
import getpass
import requests
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('username')
parser.add_argument('-p', '--password')
args = parser.parse_args()
if not args.password:
args.password = getpass.getpass("Password")
auth = (args.username, a... |
# Generates RegisterCodegenUnboxedKernels.cpp, UnboxingFunctions.h and UnboxingFunctions.cpp.
import argparse
import os
import pathlib
from dataclasses import dataclass
from tools.codegen.api import unboxing
from tools.codegen.api.translate import translate
from tools.codegen.api.types import CppSignatureGroup
from too... |
<reponame>hoffmannmatheus/eaZy<filename>apps/device_controller/zwave_controller.py
import sys, os
import openzwave
from openzwave.node import ZWaveNode
from openzwave.value import ZWaveValue
from openzwave.scene import ZWaveScene
from openzwave.controller import ZWaveController
from openzwave.network import ZWaveNetw... |
<reponame>zizai/gym-electric-motor
import numpy as np
from scipy.optimize import root_scalar
from .conf import default_motor_parameter
import warnings
class _DcMotor(object):
"""
The _DcMotor and its subclasses implement the technical system of a DC motor. \n
This includes the system equations, t... |
<gh_stars>0
# Copyright wavedrompy contributors.
# SPDX-License-Identifier: MIT
# Translated to Python from original file:
# https://github.com/drom/wavedrom/blob/master/src/WaveDrom.js
from math import floor
import svgwrite
from .base import SVGBase
from .tspan import TspanParser
class Options:
def __init__(s... |
from collections import defaultdict
import numpy as np
from day import Day
class BeaconVector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self._facings = None
def __hash__(self):
return hash((self.x, self.y, self.z))
def dist(self, other):
... |
<reponame>CryptoRichy/OctoBot<filename>tests/unit_tests/trading_tests/test_order.py
import random
import ccxt
from trading.exchanges.exchange_manager import ExchangeManager
from config.cst import TradeOrderSide, SIMULATOR_LAST_PRICES_TO_CHECK, TraderOrderType, OrderStatus
from tests.test_utils.config import load_test... |
<reponame>gonrin/gatco_kafka<gh_stars>0
import asyncio
import confluent_kafka
from confluent_kafka import KafkaException
from time import time
from threading import Thread
__version__ = '0.1.0'
class AIOProducer:
def __init__(self, configs, loop=None):
self._loop = loop or asyncio.get_event_loop()
... |
import numpy as np
import wandb
from pytorch_lightning import Callback, Trainer
from pytorch_lightning.loggers import LoggerCollection, WandbLogger
from torch import sigmoid
def get_wandb_logger(trainer: Trainer) -> WandbLogger:
"""Safely get Weights&Biases logger from Trainer."""
if isinstance(trainer.logge... |
<filename>dps/tf/train.py
import tensorflow as tf
import time
from dps import cfg
from dps.train import TrainingLoop, TrainingLoopData
from dps.utils import flush_print as _print, gen_seed
from dps.utils.tf import (
uninitialized_variables_initializer, trainable_variables, walk_variable_scopes
)
class TensorFlow... |
<filename>userbot/modules/sudo.py
# Copyright 2021 (C) FaridDadashzade.
#
# CyberUserBot - Faridxz
#
# oğurlayan peysərdi #
import os
import re
from userbot.cmdhelp import CmdHelp
from userbot.events import register
from userbot import (
HEROKU_APPNAME,
HEROKU_APIKEY,
SUDO_VERSION,
SUDO_ID,
bot,
)... |
"""
Test for RFlink sensor components.
Test setup of rflink sensor component/platform. Verify manual and
automatic sensor creation.
"""
from datetime import timedelta
from homeassistant.components.rflink import CONF_RECONNECT_INTERVAL
from homeassistant.const import (
EVENT_STATE_CHANGED,
STATE_OFF,
STATE... |
<gh_stars>10-100
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from models.BaseModel import BaseModel
class DownsamplerBlock(nn.Module):
def __init__(self, ninput, noutput):
super(DownsamplerBlock, self).__init__()
self.ninput = ninput
... |
<gh_stars>0
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
import numpy as np
def alpha_pass(OBS, A, B, Pi):
'''
OBS = (1 x k)
A = (n x n)
B = (n x m)
Pi = (1 x n)
alpha = (n x k)
'''
alpha = np.zeros((A.shape[0], OBS.shape[1]))
alpha[:, [0]] = Pi.transpose() * B[:, OBS[:, 0]] # Use Pi to calculate for the first colu... |
"""Catalyst class and its metaclass."""
import inspect
from collections import namedtuple
from typing import Iterable, Callable, Any, Mapping
from functools import wraps, partial
from .base import CatalystABC
from .fields import BaseField, FieldDict, Field
from .groups import FieldGroup
from .exceptions import Valida... |
# The MIT License (MIT)
# Copyright (c) 2018 Massachusetts Institute of Technology
#
# Author: <NAME>
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softwa... |
<filename>deeplearning1/nbs/Homework_2/organize_data.py
#!/home/ubuntu/anaconda2/bin/python
from collections import defaultdict
import os
import sys
import numpy as np
import shutil
def read_label_mapping(l_file):
l_dict = defaultdict(list)
with open(l_file) as ifh:
for line in ifh:
(f, l) ... |
from Pipeline.Authentication import Authentication
import requests
import json
import copy
from pprint import pprint
import time
def find_snomedct_server(term):
apikey = "ca310f05-53e6-4984-82fd-8691dc30174e"
AuthClient = Authentication(apikey)
version = "2017AB"
tgt = AuthClient.gettgt()
query = {... |
<filename>tests/test_code_snippets.py
import os
import glob
def test_code_snippets(parser):
this_file = os.path.realpath(os.path.dirname(__file__))
root_path = os.path.split(os.path.abspath(os.path.join(this_file)))[0]
snippets_path = os.path.join(root_path, "tests", "code_snippets", "*.c")
example... |
<filename>tk_builder/widgets/image_canvas.py
# -*- coding: utf-8 -*-
"""
This module provides functionality for
"""
import PIL.Image
from PIL import ImageTk
import platform
import time
import tkinter
import tkinter.colorchooser as colorchooser
from typing import Union, Tuple, List, Dict
import numpy
from scipy.linalg... |
<filename>add_item_window.py
import pygame
from text_box import text_box
from item import item
from buttom import buttom
def add_item(text_input_boxes):
new_thing = []
for i in text_input_boxes:
new_thing.append(i.return_text())
context, level, state, color, date = new_thing
new_thing... |
from typing import Optional
import re
class Milepost:
def __init__(self):
self.sustrans_ref = None
self.wiki_sustrans_ref = None
self.wiki_region = None
self.wiki_milepost_type = None
self.wiki_location = None
self.wiki_osm_link = None
self.osm_id = None
... |
#!/usr/bin/python
#
# Copyright (c) 2018 <NAME>, <<EMAIL>>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: azure_rm_aks_info
short_description: Get Az... |
<filename>jschon/translation.py<gh_stars>0
from __future__ import annotations
from decimal import Decimal
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from jschon.exceptions import RelativeJSONPointerError
from jschon.json import JSON, JSONCompatible
from jschon.jsonpatch import JSONPatch, JSO... |
<gh_stars>1-10
import jieba
file1 = open(r'data.csv', 'r', encoding='utf-8')
lines = file1.readlines()
true_information_need_help = []
true_information_offer_help = []
true_information_other = []
for idx, line in enumerate(lines):
classes = line.split(',')[7].strip()
if classes.startswith("求救"):... |
# -*- encoding: utf-8 -*-
'''
@Description :一个基本的component,可以直接运行在一个运行环境里
@Date :2021/04/19 10:25:11
@Author :lzm
@version :0.0.1
'''
from onceml.types.artifact import Artifact
from onceml.types.channel import Channels, OutputChannel
from onceml.types.state import State
from typing import Any, Dict, List, Optional, ... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
<reponame>Yuibooo/pytorch-soft-actor-critic
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
from utils import soft_update, hard_update
from model import GaussianPolicy, QNetwork, DeterministicPolicy
device = torch.device("cuda" if torch.cuda.is_available() else "c... |
#
# @file TestSBase.py
# @brief SBase unit tests
#
# @author <NAME> (Python conversion)
# @author <NAME>
#
# ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
#
# DO NOT EDIT THIS FILE.
#
# This file was generated automatically by converting the file located at
# src/sbml/test/TestSBa... |
from __future__ import absolute_import, print_function, unicode_literals
# Do this before importing anything else, we need to add bundled requirements
# from the distributed version in case it exists before importing anything
# else.
# TODO: Do we want to manage the path at an even more fundametal place like
# kolibri... |
#!/usr/bin/env python
import sys
import numpy as np
import matplotlib.ticker as ticker
import scipy.spatial.distance as spd
import scipy.cluster.hierarchy as sph
from scipy import stats
import matplotlib
#matplotlib.use('Agg')
import pylab
import pandas as pd
from matplotlib.patches import Rectangle
from mpl_toolkits... |
<reponame>Xxhhj1/doc-generate-1
from nltk import WordNetLemmatizer
from sekg.constant.code import CodeEntityCategory
from sekg.pipeline.component.base import Component
from sekg.text.extractor.domain_entity.identifier_util import IdentifierInfoExtractor
from sekg.text.spacy_pipeline.pipeline import PipeLineFactory
from... |
<reponame>burhandodhy/CNTK<gh_stars>1000+
# =============================================================================
# copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==========================================... |
<filename>redbrick/export/public.py
"""Public API to exporting."""
import asyncio
from typing import List, Dict, Optional, Tuple, Any
from functools import partial
import os
import json
import copy
from datetime import datetime
from shapely.geometry import Polygon # type: ignore
import skimage
import skimage.morpho... |
<filename>pyod/test/test_data.py
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import os
import sys
import unittest
from sklearn.utils.testing import assert_equal
# noinspection PyProtectedMember
from sklearn.utils.testing import assert_allclose
from sklearn.utils.test... |
import os
import random
import time
import WifiConnUtility
from NativeLog import NativeLog
from TCAction import TCActionBase
from Utility import Encoding
from Utility import MakeFolder
STEPS = {"SCAN1": 0x01, "JAP": 0x02, "SCAN2": 0x04, "RECONNECT": 0x08}
AP_PROP = ("ssid", "ssid_len", "pwd",
"pwd_len", "... |
# -*- coding: utf-8 -*-
"""
name: demo_ncnn.py
date: 2020-12-16 11:21:07
Env.: Python 3.7.3, WIN 10
"""
import argparse
from abc import ABCMeta, abstractmethod
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import softmax
from tqdm import t... |
'''
Created on 09. Okt. 2016
@author: chof
'''
from . import astring
from .gitanalyzer import GitAnalyzer
from .db import DbDump
from shutil import copyfile
from os.path import join as joinPath, basename, isfile
class DBConfig(object):
def __init__(self, cfg):
'''
Constructor
'''
... |
<reponame>861934367/genecast<filename>build/lib/genecast_package/cnv_analysis.py
## this tool is for cnv analysis
## author: taozhou
## email: <EMAIL>
import pandas as pd
from glob import glob
import numpy as np
import os
from genecast_package.core import make_result_folder
from genecast_package.snv_analysis ... |
<reponame>mbattistello/lambda_converters
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instance... |
"""
A utils for Markdown
html : render markdown to html
toc : Get the Table of Content
extract_images: Return a list of images, can be used to extract the top image
"""
import os
import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension
from jinja2.nodes import CallB... |
<filename>signin/jd_job/bean_app.py
import json
import random
from .common import RequestError, Job
class BeanApp(Job):
"""
京东客户端签到领京豆. 由于是 App (Mobile) 端页面, 登录方式与领钢镚的相同, 不同于电脑端领京豆.
"""
job_name = '京东客户端签到领京豆'
index_url = 'https://bean.m.jd.com'
info_url = 'https://api.m.jd.com/client.action... |
<filename>bnl_ml_examples/supervised/data.py<gh_stars>1-10
from pathlib import Path
import h5py
from sklearn.model_selection import train_test_split
import numpy as np
def load_data(data_dir, uniform=True, seed=1234):
"""
Loads min/max normalized data according to split preference
Parameters
--------... |
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
import logging
import unittest
from unittest.mock import Mock, patch, MagicMock
from github import Github
import cla
from cla.models.github_models import get_pull_request_commit_authors, handle_commit_from_user, M... |
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
"""
Game logic for Tron game.
<NAME>, Feb 2 2010
minor edits by <NAME>, Jan 2014
"""
import random
class Board:
def __init__(self, w, h, start=None, layout=None, outerwall=True):
''' w: width
h: height
start:
"symrand" for symmetrically random (default)
... |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2012 California Institute of Technology. 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 th... |
<reponame>zhangqf-lab/RIP-icSHAPE-MaP
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def ref_profile(MD_tag):
"""
MD_tag -- 59A11/51^CT18/6G4C20G1A5C5A1^C3A15G1G15
Return the profile corresponding to the raw sequence
"""
profile = ""
current = ""
... |
import numpy as np
import pandas as pd
class VisualizationModel(dict):
'''
classifier_ = {'type':'quantiles', 'category_count': 4, 'color_grades':[(.9,.9,.9),(0,0,1.0)], 'radii_grades': [25,300] }
'''
def __init__(self, inpt={}):
super(VisualizationModel, self).__init__(inpt)
# set up... |
<gh_stars>0
import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import mrcnn.utils
import mrcnn.model as modellib
from mrcnn import visualize
# Root directory of the project
ROOT_DIR = os.path.abspath("./")
# Import Mask RCNN
sys.path.a... |
<gh_stars>0
import random
# The Game Board
def showBoard():
print("+---+---+---+")
print("|", board[0], "|", board[1], "|", board[2], "|")
print("+---+---+---+")
print("|", board[3], "|", board[4], "|", board[5], "|")
print("+---+---+---+")
print("|", board[6], "|", board[7], "|", board[... |
import os
import pickle
import timeit
import cProfile
import itertools
import threading
from math import ceil
from binascii import hexlify
from time import perf_counter as now
import synapse.cortex as s_cortex
from numpy import random
NUM_PREEXISTING_TUFOS = 1000
NUM_TUFOS = 100000
NUM_ONE_AT_A_TIME_TUFOS = 100
H... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.