text stringlengths 2 999k |
|---|
# 5.3 Monte Carlo Control
# Monte Carlo ES (Exploring Starts) with first visit constraint
# reference: https://github.com/dennybritz/reinforcement-learning/blob/master/MC/MC%20Control%20with%20Epsilon-Greedy%20Policies%20Solution.ipynb
from collections import defaultdict
import numpy as np
import sys
if "../" not in ... |
from csv import DictReader
from datetime import datetime
import logging
from pprint import pprint
import sys
from time import sleep
import click
import requests
from rich.console import Console
from rich.logging import RichHandler
from rich.prompt import Confirm, Prompt
from rich.progress import Progress
from rich.sta... |
# Sky
# Feb 25, 2018
# Some math for video about distance between planets
import sys
# constants for objects
d_from_s_mercury = 57.91e9 # m
d_from_s_venus = 108.2e9 # m
d_from_s_earth = 149.6e9 # m
d_from_s_mars = 227.9e9 # m
d_from_s_jupiter = 778.5e9 ... |
from contextlib import closing
import subprocess
import logging
import do
logger = logging.getLogger("Main")
def g37_map(out_fn):
url_map = "http://ftp.ncbi.nlm.nih.gov/genomes/Homo_sapiens/ARCHIVE/ANNOTATION_RELEASE.105/Assembled_chromosomes/chr_accessions_GRCh37.p13"
url_ann = "http://ftp.ncbi.nlm.nih.gov/... |
from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect
from .models import Cliente, Serviço, Agendamento,Modelo, Pagamento
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.mo... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
import torch
from d2go.runner import create_runner
from detr.util.misc import nested_tensor_from_tensor_list
from fvcore.nn import flop_count_table, FlopCountAnalysis
class Tester(unittest.TestCase):
@s... |
from collections import defaultdict
import pytest
from dagster import (
DagsterEventType,
ModeDefinition,
NodeInvocation,
PipelineDefinition,
build_hook_context,
check,
execute_pipeline,
graph,
op,
pipeline,
reconstructable,
resource,
solid,
)
from dagster.core.defin... |
import importlib
from inspect import isclass
from jeri.core.models import Model
class Application:
def __init__(self, app_name, backend, models):
self.app_name = app_name
self.backend = backend
self.load_models(models)
def load_models(self, models):
if not hasattr(self, '_mo... |
from napari.layers.shapes._shapes_utils import (
generate_2D_edge_meshes,
) # , old_generate_2D_edge_meshes
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig, axes = plt.subplots(2, 3)
# fig.set_figwidth(15)
# fig.set_figheight(10)
colors = iter(['red', 'green', 'blue', 'yellow'])
itaxes ... |
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'onlinecourse'
urlpatterns = [
# route is a string contains a URL pattern
# view refers to the view function
# name the URL
path(route='', view=views.CourseListView.as... |
__all__ = ("styles",)
try:
from RichConsole import groups
styles = {
"ksyName": groups.Fore.lightgreenEx,
"resultName": groups.Fore.lightredEx,
"operationName": groups.Fore.yellow,
"info": groups.Fore.lightblueEx,
}
except BaseException:
def dummy(arg):
return arg
styles = {
"ksyName... |
from urllib.parse import quote
import requests
class Http_operation:
'''
这是一个用于简单操作http api的类
具有post发送信息的函数和post发送文件的函数
具有的参数有:
url 提交的url链接 包含域名以及api等路由
data 用于提交的字符串
file_path 被上传文件的路径(目前只支持图片)
'''
def __init__(self,url,data,file_path):
self.url = url
self.data = data
self.file_path = file_path
... |
#Import dependencies
import tensorflow as tf
from keras.models import Sequential
from keras.layers import LSTM, Bidirectional, Activation, Dropout, Dense,CuDNNLSTM, Embedding,GRU, CuDNNGRU
from keras.callbacks import *
from keras.optimizers import Adam
from keras.utils import np_utils
import numpy as np
import pandas a... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('evaluation', '0033_remove_likert_and_grade_answer'),
]
operations = [
migrations.AddField(
model_name='course',
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import copy
import math
from fu... |
# django
from django.core.urlresolvers import reverse
from django.test import TestCase, RequestFactory, Client
# own modules
from .factories import UserFactory
from .utils import url_with_querystring
from django.contrib.auth.models import User
class HomePageTest(TestCase):
"""
Tests for home page
"""
... |
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# Th... |
# -*- coding: utf-8 -*-
# @Time : 2021/3/14 17:37
# @Author : aurorazeng
# @File : __init__.py.py
# @license: (C) Copyright 2021-2026, aurorazeng; No reprobaiction without permission. |
import sys
class Graph:
def __init__(self, edges):
self._build_graph(edges)
self._compute_indgrees()
def _build_graph(self, edges):
self.nodes = []
self.adjacency_list = []
node_label_dict = dict()
for edge in edges:
... |
"""
DeepLabCut2.0 Toolbox (deeplabcut.org)
© A. & M. Mathis Labs
https://github.com/AlexEMG/DeepLabCut
Please see AUTHORS for contributors.
https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS
Licensed under GNU Lesser General Public License v3.0
"""
from __future__ import print_function
import wx
import cv2
imp... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import json
from collections import OrderedDict
from keycloak.admin import KeycloakAdminBase
POLICY_TYPES = {
'role'
}
class Policies(KeycloakAdminBase):
_paths = {
'collection': '/auth/admin/realms/{realm}/clients/{'
'client_id}/authz/resource-server/policy?permission'
... |
# copied from https://github.com/djrobstep/pgnotify/blob/43bbe7bd3cedfb99700e4ab370cb6f5d7426bea3/pgnotify/notify.py
# This is free and unencumbered software released into the public domain.
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as ... |
l=[]
z=[]
def selection_sort(l):
for i in range(0,5):
MIN=min(l)
z.append(MIN)
l.remove(MIN)
return z
print("Enter Integer list of 5 values")
for i in range(0, 5):
x = int(input())
l.append(x)
print("List is: ",l)
print("Sorted list is: ",selection_sort(l))
|
#!/usr/bin/env python
#
# Copyright 2016 Google 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 requir... |
"""
An implementation of the SMV image reader for ADSC images. Inherits from
FormatSMVADSC, customised for old detector on Diamond Light Source I03,
correctly accounting for the image pedestal & similar
"""
from __future__ import absolute_import, division, print_function
from dxtbx.format.FormatSMVADSCSN import Format... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrysoda
import os
current_path = os.path.abspath(os.path.dirname(__file__))
cherrysoda.pack_atlas(current_path, verbose=True, args='-j -p -u -s2048')
cherrysoda.update_assets()
|
"""
==============================================================
Restricted Boltzmann Machine features for digit classification
==============================================================
For greyscale image data where pixel values can be interpreted as degrees of
blackness on a white background, like handwritten... |
import matplotlib.pyplot as plt
import codecs as co
import os
import sys
import numpy as np
if len(sys.argv) > 1:
LF = sys.argv[1]
else:
LF = './log/loss_record'
AF = './infer_precision'
# ADF = './ad_losses'
# GNG = './gng_losses'
plt.figure(figsize=(22,12))
def full_arr(arr, target):
while(len(arr) < ... |
import re
from datetime import datetime
from time import mktime
#import time
def decode_filename(fn):
"""Parse a filename for a string of numbers and translate to a date
Parameters
----------
fn : string
Returns
_______
s : float
Number of seconds since epoch began
TODO:
... |
import argparse
from os import makedirs
from pathlib import Path
from urllib import request
BASE_URL = "https://github.com/numediart/MBROLA-voices/raw/master/data/%s/%s"
MBROLA_FOLDER = Path("/usr/share/mbrola/")
LANG_FILES = {'cn': [1],
'ir': [1],
'hu': [1],
'ar': [2, 1],
... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from ... |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2019 Gehtsoft USA LLC
# Licensed under the license derived from 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://fxcodebase.com/licenses/open-source/license.html
# Unless required by ap... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
"""
Copyright 2020 The OneFlow 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 required by applicable law or agr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao'
import os, sys, time, subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def log(s):
print('[Monitor] %s' % s)
class MyFileSystemEventHander(FileSystemEventHandler):
def __init__(s... |
#!/usr/bin/python3
"""
Test file for city class
"""
import unittest
from models.engine.file_storage import Objects
from models.base_model import BaseModel
class TestClass(unittest.TestCase):
"""Test cases"""
def test_create_istance(self):
"""create a new instance"""
new_city = BaseModel()
... |
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets
from tqdm import tqdm
from pixelsnail import PixelSNAIL
def train(epoch, loader, model, optimizer, device):
loader = tqdm(loader)
criterion = nn.CrossEntropyLoss(... |
#!/usr/bin/env python
""" provides a storage layer for meta-data and snv distances from the
findneighbour4 system in a RDBMS
Tested with:
- Oracle Autonomous (ATP and ADW cloud service)
- Sqlite (but, sqlite can't be used as a server backend)
Not tested:
MS SQL server, PostgreSQL
Tested but doesn't work at present
M... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
import requests
"""
HTTPS Proxy and SOCKS proxy support
- Added 09/03/2012 by Cal Leeming (Simplicity Media Ltd)
"""
# Ensure socks5 is working
# This has been tested against 'dante-server'
... |
from rest_framework import generics
from .models import Product
from .serializers import ProductSerializer
class ProductList(generics.ListAPIView):
serializer_class = ProductSerializer
queryset = Product.objects.all()
class RetrieveProduct(generics.RetrieveUpdateAPIView):
serializer_class = ProductSerializer
q... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... |
import pandas as pd
p = pd.read_csv('train.csv')
path1 = p.iloc[:, 0]
path2 = p.iloc[:, 1]
label = p.iloc[:, 2]
mat = []
for i in range(1, 12000):
if label[i] == 1:
gul = set()
for j in range(i, 40+i):
try:
if path2[j].split('/')[1] != path1[i].split('/')... |
import uuid
import time
import datetime
import pymongo
from config import config
connection = config.initdb()
db = connection.scope_db
STR_NEW = "new"
STR_PROGRESS = "progress"
def scheduling_job():
jobID = uuid.uuid4()
print("===================Run Scheduling Job ID (%s)=====================" % jobID)
... |
# Copyright 2018 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
import pook
import pytest
import requests
def test_json_operator(should):
with pook.use():
pook.get('foo.com', reply=200, response_json={'foo': 'bar'})
res = requests.get('http://foo.com')
res | should.have.json.equal.to({'foo': 'bar'})
with pytest.raises(AssertionError):
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from contextlib import contextmanager
import os
import random
import re
import warnings
import numpy as np
import tqdm
from tqdm.auto import tqdm as tqdm_auto
import jax
from jax import device_put,... |
# Copyright 2015 The TensorFlow 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 required by applica... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
import torch.nn as nn
from collections import defaultdict
import copy
from musco.pytorch.compressor.compress import get_compressed_model
class Compressor():
"""
Class to perform automated compression using VBMF rank selection.
Layers of type nn.Conv2d 1x1 and nn.Linear are decomposed using SVD, nn.Conv2... |
# Copyright 2017 The TensorFlow 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 required by applica... |
from gym_pathplan.envs.stl_pathplan import STL_Problem_Preprocess |
# -*- coding: utf-8 -*-
# Autogenerated on 09:16:59 2017/04/05
# flake8: noqa
from __future__ import absolute_import, division, print_function, unicode_literals
import utool
print, rrr, profile = utool.inject2(__name__)
def reassign_submodule_attributes(verbose=1):
"""
Updates attributes in the __init__ modul... |
"""
Modules for core training, evaluation, and W&B logging processes
"""
from .callbacks import CustomCheckpointCallback, CustomWandbCallback
from .trainer import OnlineBenchmarkTrainer
|
# Note: do not import this file directly, it is meant to be used as part of
# a Python script (generatePythonCode) that sets up variables that this
# module depends on
import string
import os
import glob
import FFIEnvironment
import FFITypes
import FFISpecs
import FFIRename
import FFIConstants
import FFIOverload
fro... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# By L2J_JP SANDMAN
import sys
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.gameserver.model.quest import QuestState
from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest
qn = "654_JourneytoaSettlement"
#NPC
SPIRIT = 31453 #Nameless Spirit
#TARGET
TARGET_... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'InfoDlg.ui'
#
# Created by: PyQt5 UI code generator 5.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialo... |
# Adding parent directory to the PYTHONPATH
import sys
sys.path.insert(0,'..')
from utils.GlobalVariables import *
class DataLoader(object):
# This class load the data of a given pair
# IMPORTANT Make sure that the type of 'date' column values in the loaded data is panda.TimeStamp
def __init__(self, pair, 1M = Fals... |
from __future__ import print_function, absolute_import
import sys
import platform
import llvmlite.binding as ll
import llvmlite.llvmpy.core as lc
from numba import _dynfunc, config
from numba.callwrapper import PyCallWrapper
from .base import BaseContext, PYOBJECT
from numba import utils, cgutils, types
from numba.u... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', 'BaxA'])
M... |
"""
.. currentmodule:: mne_bids
====================================
08. Convert iEEG data to BIDS format
====================================
In this example, we use MNE-BIDS to create a BIDS-compatible directory of iEEG
data. Specifically, we will follow these steps:
1. Download some iEEG data from the
`MNE-ECo... |
from setuptools import setup
requirements = []
with open('requirements.txt') as f:
requirements = f.read().splitlines()
extras_require = {
}
readme = ''
with open('README.md') as f:
readme = f.read()
setup(name='WarframeAlertBot',
version='0.0.1-dev',
description='Discord bot that will post... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.contrib.gis.geos import LineString, Point
from django.conf import settings
from geotrek.common.utils import almostequal
from geotrek.core.factories import PathFactory, TopologyFactory, NetworkFactory, UsageFactory
from geotrek.core.models import Pat... |
"""Manages the local state of the semantic instances"""
import copy
import json
import logging
from math import inf
import requests
from typing import Optional, Dict, Type, List, Any, Union, Set
from pydantic import BaseModel, Field
from rapidfuzz import process
from filip.models.base import NgsiVersion
from filip.... |
"""Emoji
Available Commands:
.deploy"""
from telethon import events
import asyncio
from uniborg.util import admin_cmd
from userbot import AUTONAME
from userbot import ALIVE_NAME
DEFAULTUSER = str(AUTONAME) if AUTONAME else "ArianaUserBot"
@borg.on(admin_cmd(pattern=r"deploy"))
async def _(event):
if eve... |
import os
import json
def load_map_data():
map_file_name = "map_new.json"
# map_file_name = "DC_map.json"
with open(map_file_name, encoding="utf8") as map_file:
raw_map_dict = json.load(map_file)
map_info_dict = {"node": {}, "way": {}}
for element in raw_map_dict["elements"]:
... |
from pyforms import conf
import logging, traceback
logger = logging.getLogger(__file__)
if conf.PYFORMS_MODE in ['GUI', 'GUI-OPENCSP']:
from pyforms.gui.Controls.ControlBase import ControlBase
from pyforms.gui.Controls.ControlText import ControlText
from pyforms.gui.Controls.ControlBoundingSlider import ControlBo... |
"""init py module."""
|
"""Provide a model for the Z-Wave JS node."""
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypedDict, Union, cast
from ..const import (
INTERVIEW_FAILED,
CommandClass,
NodeStatus,
PowerLevel,
SecurityClass,
)
from ..event import Event
from ..excepti... |
import _plotly_utils.basevalidators
class TexttemplateValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="texttemplate", parent_name="funnel", **kwargs):
super(TexttemplateValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_na... |
from kairosdbclient.exceptions import RequestException
from kairosdbclient.rest.apirequests.base import Request
from kairosdbclient.rest.resources import MetricTags
class QueryMetricTagsRequest(Request):
uri = 'datapoints/query/tags'
resource = MetricTags
success_status_code = 200
request_method = 'PO... |
from enum import Enum
class ProjectStatus(Enum):
ACTIVE = "ACTIVE"
INACTIVE = "INACTIVE"
|
# -*- coding:utf-8 -*-
# uLSIF
import numpy as np
class LSIF:
"""
Density radio estimation of uLSIF (Sugiyama) using RBF kernel
r(sample) = P_x(sample) / P_y(sample)
example:
LSIF(0.3, 0.1).fit(sample_molecule, sample_denominator).predict(sample_new)
"""
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# License: BSD-3 (https://tldrlegal.com/license/bsd-3-clause-license-(revised))
# Copyright (c) 2022, QuatroPe
# All rights reserved.
# =============================================================================
# DOCS
# =================================================... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_USERNAME, CONF_PASSWORD, CONF_SENSORS
from esphome.core import coroutine_with_priority
from esphome.core import CORE
DEPENDENCIES = ['network']
AUTO_LOAD = ['http_request']
influxdb_ns = cg.esphome_ns.namespace... |
# qubit number=3
# total number=73
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from... |
''' Polymorphism : Part 1
Polymorphism basically means the ability to take or have multiple or various forms.
Polymorphim means the ability to take or have various forms.
Polymorphism: Part 2 30
# Polymorphism: Part 3 60
Creating a polymorphic class method. ... |
#!/usr/bin/env python
# coding=utf-8
## @package biopredyn
## Copyright: [2012-2019] Cosmo Tech, All Rights Reserved
## License: BSD 3-Clause
import libsedml
import model, simulation, result, change, ranges
## Abstract representation of an atomic task in a SED-ML work flow.
class AbstractTask:
## @var id
# A uni... |
from datetime import datetime
from decimal import Decimal
from unittest.case import TestCase
from uuid import uuid4
from eventsourcing.application import AggregateNotFound, Repository
from eventsourcing.domain import TZINFO, Aggregate, Snapshot
from eventsourcing.persistence import (
DatetimeAsISO,
DecimalAsSt... |
#!/usr/bin/python3.6
###############################################################################
# Copyright (c) 2018, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# ... |
# Copyright 2017-2019 Damien Goutte-Gattat. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.SeqIO su... |
#!/usr/bin/env python
# coding: utf-8
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='letslog',
packages = ['letslog'],
version='0.0.3',
license='MIT',
author='YiFei Li',
author_email='yifeil@berkeley.edu',
description='A logge... |
import numpy as np
import xarray as xr
import exceptions
from dakota_file import DakotaFile
# Create a new instance of the
my_netcdf = DakotaFile()
filename = 'DAKOTA.nc'
my_netcdf.read(filename)
# We can read one of the variables in the netcdf file back into a dictionary of data
# We shall read test_normal2 which ... |
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
'''OpenGL extension NV.present_video
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_NV_present_video'
_DEPRECATED = False
GL_FRAME_NV = consta... |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
from... |
from typing import Union
import numpy as np
import torch
from torch import nn
from continual_learning.scenarios.tasks import Task
def get_accuracy(encoder: torch.nn.Module, solver: torch.nn.Module,
task: Task, batch_size=64, device='cpu'):
with torch.no_grad():
encoder.eval()
so... |
import argparse
import json
import os
import sys
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {
"argv": [sys.executable, "-m", "JWLX_kernel", "-f", "{connection_file}"],
"display_name": "JWLX",
"language": "text",
}
def install... |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The TavecchiacoinPay Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node responses to invalid transactions.
In this test we connect to one node over p2p, an... |
import socket
import timeit
import numpy as np
from PIL import Image
from datetime import datetime
import os
import sys
import glob
from collections import OrderedDict
sys.path.append("../../")
# PyTorch includes
import torch
import pdb
from torch.autograd import Variable
import torch.optim as optim
from torchvision i... |
# coding: utf-8
from logging import getLogger
from ptrlib.util.encoding import *
from ptrlib.pwn.tube import *
from ptrlib.pwn.winproc import *
import errno
import select
import os
import subprocess
import time
_is_windows = os.name == 'nt'
if not _is_windows:
import fcntl
import pty
import tty
logger = g... |
from typing import List
"""
time: O(N)
space: O(N)
"""
"""
- use a stack
- add open brace/bracket opts to stack
- when encounter a closing brace/bracket pop() from stack
- verify
ex:
- s = '{[]}'
add '{' to stack
add '[' to stack
"""
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == ... |
# Copyright (c) 2020, 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.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import math
def get_one_digit_factors(n):
candidates = [2, 3, 5, 7]
factors = [0, 0, 0, 0]
for i, candidate in enumerate(candidates):
while n % candidate == 0:
n = n // candidate
factors[i] += 1
if n != 1:
raise ValueError("two digits factors")
return factors
num_cases = int(input()... |
from jax_posterior import log_posterior, grad_log_posterior, sample_prior, get_predictions
from jax import numpy as np
import numpy as onp
from bayes_implicit_solvent.samplers import random_walk_mh
if __name__ == '__main__':
perturbation_sigma = 0.2
pred_traj_thinning = 50
#n_steps = 10000
n_steps = 10... |
from setuptools import setup, find_packages
from typed_environ import __version__
extra_test = [
'pytest>=4',
'pytest-cov>=2',
]
extra_dev = [
*extra_test,
]
extra_ci = [
*extra_test,
'python-coveralls',
]
setup(
name='typed-environ',
version=__version__,
description='Load environment... |
"""This module is used for CLI module initialization and execution"""
import os
import inspect
from lightbulb.core.utils.ipc import Pipe
from threading import Thread
import imp
import sys
META = {
'author': 'George Argyros, Ioannis Stais',
'name': 'MANAGE',
'description': 'Executes Core Modules',
'ty... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
"""
import json
import os
from flask import Flask
from flask import request
from wush.common.functions import random_int
from wush.common.loggers import create_logger
from wush.wush import Wapi
# import logging
# log = logging.getLogger('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.