content stringlengths 5 1.05M |
|---|
"""helper for anaconda-project with mamba and a 'clean' condarc"""
# Copyright (c) 2021 Dane Freeman.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).parent
ROOT = HERE.parent
CONDARC = ROOT / ".github" / ".... |
"""AWS Glue Catalog Delete Module."""
import logging
from typing import Any, Dict, List, Optional
_logger: logging.Logger = logging.getLogger(__name__)
def _parquet_table_definition(
table: str, path: str, columns_types: Dict[str, str], partitions_types: Dict[str, str], compression: Optional[str]
) -> Dict[str,... |
# Scippy libs test by
# Henry Diaz
#
# MIT Licensed
import scippy as Scippy
import sys
try:
if SCIPP_PATH=='C:\\Scipp\\' or SCIPP_PATH=='~/Scipp/' or SCIPP_PATH==None:
maths = scippy_lib(Scippy.SCIPP_MATHS)
if maths == None:
print('ERROR!!')
sys.exit(1)
else:
print('ERROR!!')
sys.exit(1)
except Exc... |
# 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 agreed to in... |
r"""
Integration models
"""
import os
from .base import Model
from .scglue import AUTO, configure_dataset, SCGLUEModel
def load_model(fname: os.PathLike) -> Model:
r"""
Load model from file
Parameters
----------
fname
Specifies path to the file
"""
return Model.load(fname)
|
import os
import yaml
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("output_with", help="output file with the schedule with ours")
parser.add_argument("output_without", help="output file with the schedule without ours")
parser.add_argument("dynamic_obs", help="path ... |
import re
from utils import utils
def parse(pass_str):
m = re.search(r'(\d+)-(\d+) ([a-z]): ([a-z]+)', pass_str)
lb, ub, letter, password = m.groups()
return (int(lb), int(ub), letter, password)
def part_1(data):
count = 0
for pass_str in data:
lb, ub, letter, password = parse(p... |
import inspect
import json
import pytest
from ..manifest import Manifest
from ..item import TestharnessTest, RefTest, item_types
@pytest.mark.parametrize("path", [
"a.https.c",
"a.b.https.c",
"a.https.b.c",
"a.b.https.c.d",
"a.serviceworker.c",
"a.b.serviceworker.c",
"a.serviceworker.b.c... |
#! /usr/bin/env python3
"""
Thermal decomposition in the n-,s-C5H11 system
(two-well, two-channel, 1D ME as a function of E)
Steady-state decomposition of n-C5H11
sample output (c5h11_2a_me1d_E_w1.dat):
T[K] p[bar] w1-k2(dis) w2-k2(dis) ktot[s-1] x(w1) x(w2)
1000.0 1.000e+02 4.7452e+... |
import pygame
from pygame.sprite import Sprite
import os
class Firebar(Sprite):
"""Firebar the can collide"""
def __init__(self, hub, x, y, name='firebar', direction='LEFT'):
super().__init__()
self.name = name
self.hub = hub
self.original_pos = (x + 4, y + 28)
self.s... |
import click
from overhave.cli.db.regular import _create_all, _drop_all
class TestOverhaveDatabaseCmds:
""" Sanity tests for database operating CLI commands. """
def test_create_all(self, click_ctx_mock: click.Context, set_config_to_ctx: None) -> None:
_create_all(click_ctx_mock.obj)
def test_d... |
#!/usr/bin/env python
"""
Example demonstrating usage of App driver to manually start it and stop it.
"""
import sys, re
from testplan import test_plan
from testplan.testing.multitest import MultiTest, testsuite, testcase
from testplan.testing.multitest.driver.app import App
from testplan.common.utils.match import Lo... |
import re
from ._enums import OutId
_actions = '|'.join([
'folds',
'calls',
'checks',
'bets',
'raises',
'allin'
])
out_type = re.compile(
r'\*?(?P<out_type>[^\s]+)'
)
round_start = re.compile(
r'Game started at: '
r'(?P<date>[\d/]+) '
r'(?P<time>[\d:]+)'
)
round_id = re.compile... |
"""
Sponge Knowledge Base
Blinking LED
GrovePi board: Connect LED to D4
"""
state = False
led = None
class LedBlink(Trigger):
def onConfigure(self):
self.withEvent("blink")
def onRun(self, event):
global led, state
state = not state
led.set(state)
def onStartup():
global l... |
from flask_restful import Resource, reqparse
from .model import ListModel
class ListResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, help='Filed bane cannot be blank')
def post(self):
data = self.parser.parse_args()
name = data['na... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmfewshot.classification.models.backbones import Conv4
from mmfewshot.classification.models.utils import convert_maml_module
def test_maml_module():
model = Conv4()
maml_model = convert_maml_module(model)
image = torch.randn(1, 3, 32, 32)... |
#!/usr/bin/env python3
from lms.authentication.password_hash import hash_password
if __name__ == "__main__":
# pylint: disable=invalid-name
password = input("Please enter a password: ").encode("utf8")
salt = input("Please enter a salt (leave blank to have one created): ")
pw_hash, salt = hash_password... |
import os
basedir=os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.getenv('SECRET_KEY', 'thissecretkey')
DEBUG = False
class DevelopmentConfig(Config):
DEBUG=True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_boilerplate_main.db')
SQLALCHEMY_TRACK_M... |
#
# @lc app=leetcode id=90 lang=python
#
# [90] Subsets II
#
# https://leetcode.com/problems/subsets-ii/description/
#
# algorithms
# Medium (41.88%)
# Total Accepted: 195.2K
# Total Submissions: 466.1K
# Testcase Example: '[1,2,2]'
#
# Given a collection of integers that might contain duplicates, nums, return
# al... |
import json
from mysql.connector.pooling import MySQLConnectionPool
from mysql.connector import connect
# Read config file and get information for MySQL database
# This file contains all the functions related to the MySQL database
with open("./config.json", "r+") as config_file:
config = json.load(config_file... |
from oidctest.cp.op import parse_resource
def test_parse_resource():
a,b = parse_resource('acct:op_id.test_id@domain')
assert a == 'op_id'
assert b == 'test_id'
a,b = parse_resource(
'https://example.com/openid-client/rp-discovery-webfinger-url/joe')
assert a == 'openid-client'
assert... |
# INPUT VARIABLES:
# - ants_dir: path to ANTS directory
# - code_dir: directory in which the code resides
# - input_dir: input directory
# - output_dir: output directory
# - alignment_type: type of motion correction.
# possible values:
# translation: (translation only)
# rigid: (translation and rotation... |
import numpy as np
import pytest
import tensorflow as tf
import larq as lq
from larq.testing_utils import generate_real_values_with_zeros
@pytest.mark.parametrize("fn", [lq.math.sign])
def test_sign(fn):
x = tf.keras.backend.placeholder(ndim=2)
f = tf.keras.backend.function([x], [fn(x)])
binarized_values... |
#!/usr/bin/env python
# In case of poor (Sh***y) commenting contact [email protected]
# Basic
import sys
import os
# Testing
# import pdb
# import time, timeit
# import line_profiler
# Analysis
# import numpy as np
# import matplotlib.pyplot as plt
# import matplotlib as mpl
# import h5py
# import yaml
# from ma... |
from swift.common.utils import get_logger
from swift.proxy.controllers.base import get_container_info
from swift.proxy.controllers.base import get_account_info, get_object_info
from swift.common.swob import Request, Response
import traceback
import requests
from json import dumps
class Euler(object):
"""
Mid... |
# -*- coding: utf-8 -*-
import time
from django.db import models
from app.fail2ban import constants
class Fail2Ban(models.Model):
name = models.CharField(u"管理员输入的名称", max_length=200, null=True, blank=True)
proto = models.CharField(u"协议", max_length=50, null=False, blank=True)
internal = models.IntegerF... |
from confluent_kafka import Consumer
from confluent_kafka.admin import AdminClient
from confluent_kafka.cimpl import NewTopic
from pyctm.memory.kafka.topic_config_provider import TopicConfigProvider
class KConsumerBuilder:
@staticmethod
def build_consumer(broker, consumer_group_id, topic_config):
K... |
from module_base import ModuleBase
from module_mixins import vtkPipelineConfigModuleMixin
import module_utils
import vtk
class contourFLTBase(ModuleBase, vtkPipelineConfigModuleMixin):
def __init__(self, module_manager, contourFilterText):
# call parent constructor
ModuleBase.__init__(self, modul... |
"""
Parsing Neurolucida files.
Here we directly extract the tree and discard everything else.
It could easily be changed to extract labels and properties etc.
What could be done next is the creation of a Morphology object, possibly using labels.
Structure of Mustafa's files:
Axon ( Marker AIS (Marker Axon))
The mark... |
'''
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function,
nums is rotated at an unknown pivot index k (0 <= k < nums.length)
such that the resulting
array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
For exampl... |
from .scanplugbase import ScanPlugBase
from idownclient.scan.shodan.shodan import Shodan
from .zoomeye import ZoomEye
from .scantools import ScanTools
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""yamltodb - generate SQL statements to update a PostgreSQL database
to match the schema specified in a YAML file"""
from __future__ import print_function
import os
import sys
import getpass
from argparse import ArgumentParser, FileType
import yaml
from pyrseas.database imp... |
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
def get_img(x, folder: str="train_images"):
"""
Return image based on image name and folder.
"""
data_folder = f"{path}/{folder}"
image_path = os.path.join(data_folder, x)
img = cv2.imread(i... |
#!/usr/bin/env python
"""
@package mi.dataset.driver.spkir_abj.cspp.test
@file mi/dataset/driver/spikr_abj/cspp/test/test_spkir_abj_cspp_recovered_driver.py
@author Mark Worden
@brief Minimal test code to exercise the driver parse method for spkir_abj_cspp recovered
Release notes:
Initial Release
"""
import os
impo... |
import inspect
import warnings
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
kernels = tfp.math.psd_kernels
tfpl = tfp.layers
tfd = tfp.distributions
# Only needed for GW-OT
try:
import ot
except ModuleNotFoundError:
warnings.warn('POT package not available.')
# Probabilit... |
import cc_dat_utils
#Part 1
input_dat_file = "data/pfgd_test.dat"
#Use cc_dat_utils.make_cc_level_pack_from_dat() to load the file specified by input_dat_file
data = cc_dat_utils.make_cc_level_pack_from_dat(input_dat_file)
#print the resulting data
print(data) |
a = int(input("Enter the number:"))
if a%5 == 0 and a%11 == 0:
print(a,"is divisible by both 5 and 11.")
elif a %5 == 0:
print(a," is divisible by 5")
elif a%11 == 0:
print(a,"is divisible by 11")
else:
print(a, "is not divisible by both 11 and 5")
|
import pytest
from ruamel import yaml
from qhub.render import render_template
from qhub.initialize import render_config
@pytest.mark.parametrize(
"project, namespace, domain, cloud_provider, ci_provider, auth_provider",
[
("do-pytest", "dev", "do.qhub.dev", "do", "github-actions", "github"),
... |
from utils import read_problem
import sys
import json
problem_id = sys.argv[1]
spec = read_problem(problem_id)
def check_distance(spec, orig_dist, new_dist):
if abs(1.0 * new_dist / orig_dist - 1) <= spec['epsilon'] / 10**6:
return True
return False
def dist2(pt1, pt2):
x1, y1 = pt1
x2, y2... |
from gui import *
from player import *
game = game.Game()
# gui = Gui("Pierre", "Margot")
# gui.generate_gui()
# print("End of gui")
game.play()
|
#!/usr/local/bin/python
'''
PtpNeighbor Class
'''
import pcap
import re
import datetime
from AnnounceMessage import AnnounceMessage
from SyncMessage import SyncMessage
# =============================================================================
# PtpNeighbor
#
# Inheriting from `object` (top-level class)
# ======... |
#!/usr/bin/env python
# coding=utf-8
"""
__init__.py
"""
__author__ = 'Rnd495'
import navbar
import playerLogTable
import playerRecordsTable
import highCharts |
from Ft.Xml import EMPTY_NAMESPACE
class DebugWriter:
def __init__(self):
self.reset()
def reset(self):
self.calls = []
def getMediaType(self):
return ""
def getResult(self):
return ''
def getCurrent(self):
rt = self.calls
self.reset()
ret... |
import sys
from queue import LifoQueue
error_table = {')': 3, ']': 57, '}': 1197, '>': 25137}
match_table = {')': '(', ']': '[', '}': '{', '>': '<'}
complete_table = {'(': ')', '[': ']', '{': '}', '<': '>'}
complete_score = {')': 1, ']': 2, '}': 3, '>': 4}
def main():
if len(sys.argv) != 2:
sys.exit("Ple... |
import requests
import logging
import re
import time
import datetime
import bisect
import json
import gzip
#import hashlib
from urllib.parse import quote
from pkg_resources import get_distribution, DistributionNotFound
import os
__version__ = 'installed-from-git'
LOGGER = logging.getLogger(__name__)
try:
# this ... |
# -*- coding: utf-8 -*-
import os
import time
import hashlib
import settings
from fileoo import File
class Cache:
def __init__(self):
self.fil = File()
def fingerprint_path(self, key):
fingerprint = hashlib.md5(key).hexdigest()
cache_path = os.path.join(settings.CACHE_PATH, fingerpr... |
from datetime import datetime
from functools import total_ordering
from sqlalchemy import asc
from sqlalchemy.sql import sqltypes, schema
from sqlalchemy.exc import SQLAlchemyError
from app.database import BASE, SESSION
from app.database.utils.decorators import with_insertion_lock
from app.database.utils.filters impo... |
from floodsystem.stationdata import build_station_list
from Task2B import run
def test_Task2B():
testList = run()
assert testList[0][1] > testList[-1][1]
assert testList[-1][1] > 0.8 |
import os
from typing import IO
from abc import abstractmethod, ABCMeta
class ArquivoEntrada(object, metaclass=ABCMeta):
def __init__(self):
self.linha: str = ''
self.cont: int = 0
@abstractmethod
def ler(self, *args, **kwargs) -> None:
"""
Parametros aceitos nesse meto... |
"""This problem was asked by Google.
You are given an array of arrays of integers, where each array corresponds
to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at
a time to an ad... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
#!/usr/bin/env python
# python setup.py sdist upload -r pypi
from distutils.core import setup
version = '0.47'
packages = ['ctbBio']
scripts = ['ctbBio/16SfromHMM.py', 'ctbBio/23SfromHMM.py', 'ctbBio/numblast.py', 'ctbBio/besthits.py',
'ctbBio/calculate_coverage.py', 'ctbBio/cluster_ani.py', 'ctbBio/com... |
"""Adding new operation types
Revision ID: 1cf750b30c08
Revises: e35c7cf01cb4
Create Date: 2021-11-02 23:51:07.308510
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1cf750b30c08'
down_revision = 'e35c7cf01cb4'
branch_labels = None
depends_on = None
def upgr... |
#!/usr/bin/env python3
import rospy
import rospkg
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import pathlib
import onnxruntime as ort
import numpy as np
import cv2
from olfaction_msgs.msg import gas_sensor, anemometer
import matplotlib.pyplot as plt
# set initial position
initial_pos... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/iliadobrusin/catkin_ws/src/roc_node/msg/Motion.msg;/home/iliadobrusin/catkin_ws/src/roc_node/msg/Movement.msg;/home/iliadobrusin/catkin_ws/src/roc_node/msg/Command.msg"
services_str = ""
pkg_name = "roc"
dependencies_str = "std_msgs"
langs = "ge... |
from language import *
from generator import *
|
import tensorflow as tf
import sys
from tensorflow.python.platform import gfile
from tensorflow.core.protobuf import saved_model_pb2
from tensorflow.python.util import compat
model_filename ='./out/opt_mnist_convnet.pb'
with tf.Session() as sess:
with gfile.FastGFile(model_filename, 'rb') as f:
graph_def... |
# Copyright(C) 1999-2020 National Technology & Engineering Solutions
# of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
# NTESS, the U.S. Government retains certain rights in this software.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provide... |
import getpass
import os
import re
import subprocess
from scripts.config import *
def accept_warning(s):
c = ''
d = {'Y': True, 'y': True, 'N': False, 'n': False}
while not c in d:
c = input('Warning: %s \n Y/N? ' % s)
return d[c]
def get_env():
domain = input("Input domain : ")
usr... |
import arm
if not arm.is_reload(__name__):
arm.enable_reload(__name__)
redraw_ui = False
target = 'krom'
last_target = 'krom'
export_gapi = ''
last_resx = 0
last_resy = 0
last_scene = ''
last_world_defs = ''
proc_play = None
proc_build = None
proc_publish_build = None
... |
"""Amazon SQS queue implementation."""
from __future__ import annotations
from vine import transform
from .message import AsyncMessage
_all__ = ['AsyncQueue']
def list_first(rs):
"""Get the first item in a list, or None if list empty."""
return rs[0] if len(rs) == 1 else None
class AsyncQueue:
"""As... |
# coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup, find_packages
setup(
name='ctypes_third_party_test',
... |
from celery import shared_task
from django.conf import settings
from .models import DiscourseUser, DiscourseGroup
from .request import DiscourseRequest
from http.client import responses
import logging
logger = logging.getLogger(__name__)
@shared_task
def sync_discourse_users():
for discourse_user in DiscourseU... |
import numpy as np
from .base import IndependenceTest
from ._utils import _CheckInputs
from . import Dcorr
from .._utils import gaussian, check_xy_distmat, chi2_approx
class Hsic(IndependenceTest):
r"""
Class for calculating the Hsic test statistic and p-value.
Hsic is a kernel based independence test a... |
# CUPS Cloudprint - Print via Google Cloud Print
# Copyright (C) 2011 Simon Cadman
#
# 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 3 of the License, or
# (at y... |
from __future__ import annotations
import logging
from typing import Dict, Iterator, List, Optional, Tuple
from botovod.exceptions import HandlerNotPassed
from .types import Attachment, Chat, Keyboard, Location, Message
class Agent:
def __init__(self):
self.botovod = None
self.running = False
... |
import re
from time import sleep
from timeUtils import clock, elapsed
from ioUtils import saveFile, getFile
from fsUtils import setDir, isDir, mkDir, setFile, isFile, setSubFile
from fileUtils import getBaseFilename
from searchUtils import findSubPatternExt, findPatternExt, findExt
from strUtils import convertCurrency
... |
#!/usr/bin/env python3
from setuptools import setup
# from distutils.core import setup
with open('README.md') as f:
long_description = f.read()
setup(
name = 'py-process',
packages = ['py_process'],
version = '0.0.1',
description = 'engine processs',
long_description=long_description,
long_description_... |
import praw
import config
import json
import argparse
import datetime
reddit = praw.Reddit(client_id = config.client_id,
client_secret = config.client_secret,
username = config.username,
password = config.password,
user_agent = c... |
#!/usr/bin/env python
import os
import sys
root_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
os.chdir(root_dir)
#using virtualenv's activate_this.py to reorder sys.path
activate_this = os.path.join(root_dir, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
if ... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from CauldronHost import *
from CauldronGroup import *
from CauldronGroupHostAssoc import *
from Base import Base
from flask import Flask
from flask import jsonify
from flask_marshmallow ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="atlas_horizon",
version="0.1",
author="Ihor Kyrylenko",
author_email="[email protected]",
description="A small program to work with .ATL files and making queries to HORIZON system",
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""config
=========
The configuration is a JSON-formatted file. See ``_config_example``.
Applications may add whatever variables to the configuration file.
"""
import os
import json
import argparse
from typing import Dict, List, Optional, TypeVar, Unio... |
# Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Process Fastq files with trimmomatic
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC ## Setup
# COMMAND ----------
# MAGIC %python
# MAGIC
# MAGIC """
# MAGIC Setup some parameters
# MAGIC """
# MAGIC
# MAGIC _silver_table = "silver_fastq_trimmed"
# C... |
"""
Django settings for crsbi project.
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
For production settings see
https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
"""
import getpass
import logging
import os
from kdl_ldap.settings import * #... |
import numpy as np
from min_interval_posets import supergraph as sg
def test1():
# Insertions at ends
str1 = [('m', .5), ('M', .75), ('m', .9), ('M', .3)]
str2 = [('M', .25), ('m', .5), ('M', .7), ('m', .8)]
mat = sg.get_alignmentmat(str1, str2)
mat_round = [[round(mat[i][j],8) for j in range(len(m... |
import pandas
from variantannotation import genotype_calling
from variantannotation import utilities
#REFACTOR THIS CODEEEEE AASAP
def get_list_from_annovar_csv(df, chunk_ids):
df = df.rename(columns={'1000g2015aug_all': 'ThousandGenomeAll'})
df.Chr = df.Chr.replace(to_replace='chrM', value='chrMT')
df[... |
from rest_framework import viewsets
from .serializers import TwitterSerializer
from .models import Twitter
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse, Http404, JsonResponse
import tweepy
from rest_framework.decorators import api_view
class TwitterViewSet(views... |
import dash
from dash.dependencies import Input, Output, State
from server import app
@app.callback(
Output('steps-demo', 'current'),
[Input('steps-demo-go-next', 'nClicks'),
Input('steps-demo-go-last', 'nClicks'),
Input('steps-demo-restart', 'nClicks')],
State('steps-demo', 'current'),
pre... |
# -*- coding: utf-8 -*-
import math
import numpy as np
import pandas as pd
try:
import scipy
_SCIPY_ = True
except ImportError:
_SCIPY_ = False
from .utils import fibonacci, pascals_triangle
from .utils import get_drift, get_offset, verify_series
def weights(w):
def _compute(x):
return np.d... |
import os
GCP_PROJECT = os.environ['HAIL_GCP_PROJECT']
assert GCP_PROJECT != ''
GCP_ZONE = os.environ['HAIL_GCP_ZONE']
assert GCP_ZONE != ''
GCP_REGION = '-'.join(GCP_ZONE.split('-')[:-1]) # us-west1-a -> us-west1
DOCKER_PREFIX = os.environ.get('HAIL_DOCKER_PREFIX', f'gcr.io/{GCP_REGION}')
assert DOCKER_PREFIX != ''
... |
# Function to generate list of factors
def get_factorsList(n):
l = [1] # will be factor of any no.
# As n/2 is largest factor of n less then n
for i in range(2, n//2+1):
if n%i==0: # Check if factor or not
l.append(i)
# As we already added 1 in list no need to append it again
if n != 1:
l.append(n)
# O... |
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.tex... |
import pytest
pytest.main(['-x', 'tests', '--resultlog=run_tests.log', '-v'])
|
import xarray as xr
from numpy import abs, arange, unique
from os.path import exists
def readOOI (fname):
"""
Update parameter names from OOI to iPROF
Parameters
----------
fname : str
path of OOI Pioneer Profiler mooring downloaded data
Returns
-------
ds : xarray DataSet
... |
"""This module supports puzzles that place fixed shape regions into the grid."""
from collections import defaultdict
import sys
from typing import Dict, List
from z3 import ArithRef, Int, IntVal, Or, Solver, PbEq
from .fastz3 import fast_and, fast_eq, fast_ne
from .geometry import Lattice, Point, Vector
from .quadtre... |
from . import call
call()
|
import time
import torch
from abstraction_learning_dataset import AbstractionLearningDataSet
from abstraction_learning_CNN import AbstractionLearningCNN
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
def TrainNetwork():
use_GPU = torch.cuda.is_available()
print ("Train Abstrac... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
"""
:Author: Berk Onat <[email protected]>
:Year: 2017
:Licence: UIUC LICENSE
"""
from sys import versi... |
# Generated by Django 2.2.24 on 2021-10-22 06:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('meeting', '0049_session_purpose'),
]
operations = [
migrations.AddField(
model_name='session',
name='on_agenda',
... |
import gym
import tensorflow as tf
from tensorboardX import SummaryWriter
from agent.continuous.seperate.ppo import PPO
from agent.utils import get_gaes
from example_model.policy.mlp.continuous import MLPContinuousActor
from example_model.policy.mlp.continuous import MLPContinuousCritic
env = gym.make('BipedalWalker-... |
"""User configuration file
File organizing all configurations that may be set by user when running the
train.py script.
Call python -m src.train --help for a complete and formatted list of available user options.
"""
import argparse
import time
from random import randint
import os
import socket
import g... |
def find_median(Arr, start, size):
myList = []
for i in range(start, start + size):
myList.append(Arr[i])
myList.sort()
return myList[size // 2]
def fastSelect(array, k):
n = len(array)
if 0 < k <= n:
setOfMedians = []
arr_less_P = []
arr_equal_P = []
... |
from nbconvert.preprocessors import Preprocessor
class StripOutput(Preprocessor):
"""
Clear prompt number and output (if any) from all notebook cells.
Example
-------
# command line usage:
jupyter nbconvert example.ipynb --pre=nbexample.strip_output.StripOutput
"""
def preprocess_cell... |
#Student program - Conor Hennessy - November 2014~2016
import Test
##Defining RunTest function to run task one code
def RunTest():
Test.RunQuiz()
##Defining Savescore function with code to check for headers and get values from test
def Savedata():
print("Writing to file...")
global data
... |
# Generated by Django 3.0.8 on 2020-08-20 08:21
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@title: pm_synth.py
@date: 08/13/16
@author: Daniel Guest
@purpose: Provide classes to create phase modulation synthesizer.
"""
import numpy as np
import math
class Synth(object):
def __init__(self, fs=10000, inv_samp=50, n_op=6):
# Initiali... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 15:18:53 2020
@author: z003vrzk
"""
# Python imports
import sys, os
import unittest
# Sklearn imports
from sklearn.naive_bayes import ComplementNB
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, make_scorer, precision_score, reca... |
import numpy as np
import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib import rnn
import config
import gen_data
def lstmnet(input_tensor, label_tensor, global_step, phase, reuse_weights):
# input_tensor: [ BATCH_SIZE, SEQUENCE_LENGTH, INPUT_DIMENSION]
# label_tensor: [ BATCH... |
#!/usr/bin/python3
"""
In MATLAB, there is a very useful function called 'reshape', which can reshape a
matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.