content stringlengths 5 1.05M |
|---|
#!/bin/bash
#SBATCH --job-name=DeepTreeAttention # Job name
#SBATCH --mail-type=END # Mail events
#SBATCH --mail-user=benweinstein2010@gmail.com # Where to send mail
#SBATCH --account=ewhite
#SBATCH --cpus-per-task=10
#SBATCH --mem=30GB
#SBATCH --time=72:00:00 #Time limit hrs:min:sec
#SBATCH --ou... |
from kapteyn import maputils, wcs
from matplotlib import pyplot as plt
import numpy as np
# The data you want to re-project
Basefits = maputils.FITSimage("m101.fits")
hdrIn = Basefits.hdr
projIn = Basefits.proj
crvalsI = Basefits.proj.crval
# We want to change the sky system, so we need to know the values of CRVAL i... |
import sys
import os.path
if __name__ == '__main__' and __package__ is None:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from table import Table
from loader import load_file as load, procedures, reference_procedure
from utils import groupby
from writer import RestWriter
from pr... |
import gym
from wrappers.frame_skipper import FrameSkipper
from gym.wrappers import FrameStack, GrayScaleObservation, Monitor
class CarRacingEnv:
def __init__(self, device, seed, stack_frames=4, train=False):
super().__init__()
self.total_rew = 0
self.state = None
self.done = Fals... |
list1 = range(100, 110) #statement 1
print ("index of element 105 is : ", list1.index(105)) #statement 2
|
"""auto_self.py
-----------------
Helps to reduce the amount of typing required and increases readability
when assigning attributes in a class's ``__init__()`` method.
"""
from ideas import import_hook, utils
import token_utils
def transform_source(source, callback_params=None, **kwargs):
"""This function is cal... |
from enum import Enum, IntEnum
from .models import Error
from django.db import IntegrityError
class ErrorCodes(IntEnum):
GENERIC_ERROR = 0
UNAUTHENTICATED_REQUEST = 1
UNAUTHORIZED_REQUEST = 2
COULD_NOT_PROCESS_UPLOAD = 3
USER_CREATION_FAILED = 4
USER_UPDATE_FAILED = 5
USER_DELETION_FAILED ... |
def f(n):
if n == 0:
return 0
if n < 10:
return 1
s = str(n)
if s.count('9') == len(s):
return len(s) * 10 ** (len(s) - 1)
a = int(s[0])
b = int(s[1:])
if a == 1:
return f(n - b - 1) + (b + 1) + f(b)
else:
c = '9' * (len(s) - 1)
return f(in... |
from collections import defaultdict
from typing import List, Tuple, Union, Literal, Set, Optional
from adventofcode.util.exceptions import SolutionNotFoundException
from adventofcode.util.helpers import solution_timer
from adventofcode.util.input_helpers import get_input_for_day
class Paper:
def __init__(self, ... |
from __future__ import absolute_import
from __future__ import print_function
import autograd.numpy as np
from autograd import value_and_grad
from scipy.optimize import minimize
import matplotlib.pyplot as plt
import os
from six.moves import range
rows, cols = 40, 60
# Fluid simulation code based on
# "Real-Time Flu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lessons', '0035_auto_20180222_1511'),
]
operations = [
migrations.AddField(
model_name='lesson',
nam... |
from base_plugin import BasePlugin
from utility_functions import give_item_to_player
class NewPlayerGreeter(BasePlugin):
"""
Welcomes new players by giving them a bunch of items.
"""
name = 'new_player_greeter_plugin'
def activate(self):
super(NewPlayerGreeter, self).activate()
def a... |
import torch
from torch import nn
import numpy as np
from common.nn import SharedMLP
from mvpnet.ops.group_points import group_points
import mvpnet.models.unet_resnet34 as net2d
from functools import partial
class FeatureAggregation(nn.Module):
"""Feature Aggregation inspired by ContFuse"""
def __init__(se... |
__author__ = 'khomitsevich'
import os
import sys
class OSHelper:
""" Helper class has several methods which operate `os` system library. """
@staticmethod
def validateInputArgumentsAmount(argv: list):
if len(argv) > 2:
print("Input shouldn't has more than 1 input argument. Try again."... |
# -*- encoding: utf-8 -*-
# -----
# Created Date: 2021/1/21
# Author: Hanjing Wang
# -----
# Last Modified:
# Modified By:
# -----
# Copyright (c) 2020 MARL @ SJTU
# -----
import pytest
from .chunk import serialize, deserialize
def test_int():
a = 24
assert deserialize(serialize(a)) == a
def test_float():
... |
from .backward_kl_divergence import BackwardKLDivergence
from .forward_kl_divergence import ForwardKLDivergence
from .predicted_entropy import PredictedEntropy
from .r2 import R2
from .true_entropy import TrueEntropy
|
import doesnotexist # flake8: noqa
|
import argparse
import random
import json
import os
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('load_path', type=str,
help='The path to a json file containing video information, or a path to a folder containing '
'js... |
from games.gallows import *
from games.noughtsAndCrosses import *
def play_again():
# Returns True if the player wants to play again, false otherwise
print()
print('Do you want to play again? (yes or no)')
return input().lower() == 'yes'
def main():
# Main application entry point
... |
import json
from rest_framework.test import APITestCase, APIClient
from rest_framework.views import status
class TestArticleReadTime(APITestCase):
"""
Class tests for article .
"""
client = APIClient()
def setUp(self):
""" Creates user and user dictionary for testing."""
self.ar... |
# -*- coding: utf-8 -*-
new_d1 = {} # 创建空字典,使用{}或工厂函数dict()可以创建一个空字典
new_d2 = dict() # 创建空字典
print("Dict1:", new_d1, "Dict2:", new_d2)
new_d3 = dict(aaa=333, ccc=333, bbb=111) # 创建字典
new_d4 = dict([("abc", "123"), ('def', 456)]) # 从其它映射或键值对序列创建字典
print("Dict3:", new_d3, "Dict4:", new_d4)
testDict = { # 创建字典
... |
#! /usr/bin/env python3
import os, sys, re
def execute(args):
#if empty then return
if len(args) == 0:
return
#exit command
elif args[0].lower() == "exit":
sys.exit(0)
#cd changing directory command
elif args[0].lower() == "cd":
try:
#cd ..
if ... |
# Copyright 2020 MongoDB Inc.
#
# 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 the rights to use, copy, modify, merge, publish,
# distribu... |
from tensorflow_probability import distributions as tfpd
import tensorflow.keras.layers as tfkl
import tensorflow as tf
import numpy as np
class ForwardModel(tf.keras.Sequential):
"""A Fully Connected Network with 2 trainable layers"""
distribution = tfpd.Normal
def __init__(self, task, embedding_size=5... |
from scipy import signal
import sys
import cv2
import numpy as np
def roberts(I, _boundary='fill', _fillvalue=0):
H1,W1 = I.shape[0:2]
H2,W2 = 2,2
# 卷积核1
R1 = np.array([[1,0],[0,-1]],np.float32)
kr1,kc1 = 0,0
# 计算full卷积
IconR1 = signal.convolve2d(I,R1,mode='full',boundary=_boundary,fillval... |
import taichi as ti
from fluid_simulator import *
from ferrofluid_simulator import *
from apic_extension import *
from initializer_2d import *
from visualizer_2d import *
if __name__ == '__main__':
res = 128
solver = FerrofluidSimulator(2, (res, res), 1e-4, 1, 3.1250e-3)
# initializer = SphereInitializer2D... |
"""
Module responsible for translating sequence annotation data
into GA4GH native objects.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import random
import ga4gh.protocol as protocol
import ga4gh.datamodel as datamodel
import ga4gh.sqli... |
#!/usr/bin/env python
from threading import Thread, Event
import itertools
import time
import sys
class SpinnerThread(Thread):
spinner = itertools.cycle('|/-\\')
def __init__(self, prefix: str, suffix: str):
super(SpinnerThread, self).__init__()
self.__stop_event = Event()
self.__prefix = prefix
self.__s... |
from setuptools import setup
import pathlib
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name="Red-Dashboard",
version="0.1.4a",
description="An easy-to-use interactive web dashboard to control your Redbot.",
long_description=README,
long_descrip... |
# -*- coding: UTF-8 -*-
""" Convenient routines to set up and to tweak matplotlib plots.
"""
import vtools.data.timeseries
from schimpy.unit_conversions import m_to_ft, cms_to_cfs, celcius_to_fahrenheit,\
psu_ec_25c, psu_ec_25c_scalar, ec_sea
import palettable
from matplotlib.ticke... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector, HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from cwrealtor.items import RealtorItem, RealtorCache
from scrapy_webdriver.http import WebdriverRequest
from scra... |
from __future__ import absolute_import
from __future__ import unicode_literals
from celery.schedules import crontab
from celery.task import task, periodic_task
from celery.utils.log import get_task_logger
from corehq.apps.data_interfaces.models import (
AutomaticUpdateRule,
CaseRuleActionResult,
DomainCaseR... |
# Copyright (C) 2018-present ichenq@outlook.com. All rights reserved.
# Distributed under the terms and conditions of the Apache License.
# See accompanying files LICENSE.
import xlrd
import openpyxl
import tabugen.typedef as types
ignored_extension = [
'~$',
'-TNP-',
' - 副本',
]
def is_ig... |
"""runway env module."""
from __future__ import print_function
# pylint trips up on this in virtualenv
# https://github.com/PyCQA/pylint/issues/73
from distutils.util import strtobool # noqa pylint: disable=no-name-in-module,import-error
from subprocess import check_call, check_output
import copy
import glob
import... |
import base64
from Crypto.Cipher import PKCS1_v1_5
import hashlib
from Crypto.PublicKey import RSA
from config import app
"""
公钥签名
return base64加密字符串
"""
def EnRsaPublic(enstr):
rsakey = RSA.importKey(app.RSA_PUBLIC_KEY)
cipher = PKCS1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(enstr.en... |
import argparse
from extractor.taskdb import *
import requests
import json
from .consts import EFF_TASK_CONVERSION
parser = argparse.ArgumentParser()
parser.add_argument("--out", default="data/tasks/eff.json", help="Output JSON filename to use")
args = parser.parse_args()
URL = "https://raw.githubusercontent.com/AI-... |
class RustTime:
def __init__(self, day_length, sunrise, sunset, time, raw_time) -> None:
self._day_length: float = day_length
self._sunrise: str = sunrise
self._sunset: str = sunset
self._time: str = time
self._raw_time: float = raw_time
@property
def day_length(self... |
import os
import sys
curr_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(curr_path, ".."))
import argparse
import math
import tensorflow as tf
from PRNet.PRN import PRN
from data import read_list, write_list
import timeit
def read_index(idx_path):
if os.path.exists(idx_path):
... |
from django.urls import path
from .views import IndexView, SalaView
urlpatterns = [
path('',IndexView.as_view(), name = 'index'),
path('chat/<str:nome_sala>/', SalaView.as_view(), name = 'sala'),
] |
import threading, time
def nothing():
time.sleep(10)
t=threading.Thread(target=nothing)
t.start()
name=t.name
for i in range(100):
unfinished_thread_names = [t.name for t in threading.enumerate() if t.name in {name: 'nothing'}.keys()]
status = [tdescr for tname, tdescr in {name: 'nothing'}.items() if t... |
import unittest
import sys
import jpyutil
jpyutil.init_jvm(jvm_maxmem='512M', jvm_classpath=['target/test-classes'])
import jpy
if sys.version_info >= (3, 0, 0):
TYPE_STR_PREFIX = '<class '
else:
TYPE_STR_PREFIX = '<type '
class TestGetClass(unittest.TestCase):
def test_get_class_of_primitive_array(s... |
from libra.trusted_peers import ConsensusPeersConfig
from libra.account_address import ADDRESS_LENGTH
from libra.validator_verifier import ValidatorSet
from nacl.signing import VerifyKey
import pdb
def test_validator_set_path():
assert ValidatorSet.validator_set_path() == [1, 155, 221, 107, 26, 67, 22, 15... |
import os
import subprocess
import logging
import pickle
import json
from detect import extract_folder
logging.basicConfig(level=logging.INFO)
with open('links.pkl', "rb") as f:
links = pickle.load(f)
class downloader_and_unzipper:
def __init__(downloader):
with open('login.json', 'r') as JSON:
... |
exec "import os; os.system('echo security breach')"
|
import evaluators as E
import demand as D
import read_csv as reader
import sys
import numpy as np
from functools import partial
class MockManager():
def NodeToIndex(self,a):
return a
def IndexToNode(self,a):
return a
def test_time_callback():
pickup_time = 20
dropoff_time = 10
ho... |
"""Receba 2 cordenadas e clacule a sua distancia, sendo que se a distancia
for maior ou igual a 10 ta longe, se não esta perto"""
import math
x1 = int(input("Cordenada x1: "))
y1 = int(input("Cordenada y1: "))
x2 = int(input("Cordenada x2: "))
y2 = int(input("Cordenada y2: "))
distancia = math.sqrt(math.pow((x1 -... |
# -*- coding: utf-8 -*-
from openelevationservice.server.api.api_exceptions import InvalidUsage
from openelevationservice.server.utils import logger
from shapely.geometry import shape, LineString, Point
log = logger.get_logger(__name__)
def geojson_to_geometry(geometry_str):
"""
Converts GeoJSON to shapely ... |
#!/usr/bin/python
import os
from datetime import date
def cleanup(rootpath, cutoffdays=8):
file_list = os.listdir(rootpath)
today = date.today()
cutoff = date.fromordinal(today.toordinal() - cutoffdays)
ordinal_map = [(date(*[int(x) for x in x.split('_')[-1].split('.')[0].split('-')])) for x in file_... |
import math
import torch
import sys
import pandas as pd
import os
def calculate_air_density(air_temp, rh):
#returns air density in kg / m^3
#equation from page 13 GLM/GLEON paper(et al Hipsey)
#Ratio of the molecular (or molar) weight of water to dry air
mwrw2a = 18.016 / 28.966
c_gas = 1.0e3 * 8.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from garments.models import Garment
from garments.models import GarmentType
from garments.models import BaseGarment
from garments.serializers import GarmentSerializer
from garments.serializers import GarmentTypeSerializer
from garments.serializers import... |
import multiprocessing as mp
from .printing import nprint
from .utility import combine_versions, InvalidVersionException
from .parser import Parser
from .source_visitor import SourceVisitor
from .backports import Backports
class ProcessResult:
def __init__(self, path):
self.path = path # Path of processed... |
from multimetric.cls.base import MetricBase
class MetricBaseLOC(MetricBase):
METRIC_LOC = "loc"
_needles = [
"Token.Text"
]
def __init__(self, args, **kwargs):
super().__init__(args, **kwargs)
def parse_tokens(self, language, tokens):
super().parse_tokens(language, [])
... |
__author__ = 'Manash'
import pandas as PD
from pandas import DataFrame
import matplotlib.pyplot as plot
#read data
target_url = ("file:\\\E:\ML in python\Chapter2\sonar.all-data.txt")
#load data
rocksVMines = PD.read_csv(target_url, header =None, prefix = "V-")
dataRow2 = rocksVMines.iloc[1, 0:60]
... |
from collections import OrderedDict
expected = [
OrderedDict(
[
("type", u"web"),
("id", u"bib25"),
(
"authors",
[
OrderedDict(
[
("type", "person"),
... |
"""
Created on Dec 10, 2017
@author: jachin,Nie
A pytorch implementation of NFM
Reference:
[1] Neural Factorization Machines for Sparse Predictive Analytics
Xiangnan He,School of Computing,National University of Singapore,Singapore 117417,dcshex@nus.edu.sg
Tat-Seng Chua,School of Computing,National University... |
import pickle
import os
import collections
import SimpleITK as sitk
import nibabel as nib
import numpy as np
from nilearn.image import reorder_img, new_img_like
from .nilearn_custom_utils.nilearn_utils import crop_img_to
from .sitk_utils import resample_to_spacing, calculate_origin_offset
def pickle_dump(item, out_... |
from django.conf.urls import url
from django.contrib import admin
from contacts.views import (
contacts_nep,
)
urlpatterns = [
url(r'^$', 'contacts.views.contacts_nep'),
] |
import sys
import time
import bs4
import keyring
import requests
from .constants import *
def submit(args):
contest, problem_letter = translate_problem_name(args.problem)
with requests.Session() as s:
site = s.get('https://codeforces.com/enter')
soup = bs4.BeautifulSoup(site.content, 'html.... |
from matplotlib import pyplot as plt
import io
from PIL import Image
import cv2
import torch
import os
WIDTH = 1280
HEIGHT = 760
model = torch.hub.load("ultralytics/yolov5", "custom", path="./best.pt")
def get_prediction(img_bytes,model):
img = img_bytes
# inference
results = model(img, size=640)
... |
# -*- coding: utf-8 -*-
# @Time : 2022/3/19 8:47 上午
# @Author : Kevin
# @File : conftest.py
# @Software: PyCharm
|
import enum
import pathlib
import pandas as pd
import structlog
import us
from covidactnow.datapublic import common_df
from covidactnow.datapublic import common_init
from covidactnow.datapublic import census_data_helpers
from covidactnow.datapublic.common_fields import CommonFields
from covidactnow.datapublic.common_f... |
# 5. Design a software for bank system. There should be options like cash withdraw, cash credit and change password.
# According to user input, the software should provide required output.Hint:
# Use if else statements and functions.
from datetime import datetime
# ATM Simulation
# defaults
DEF_PIN_NUMBER = "1234"
D... |
import sys
import time
from queue import Queue, Empty
# Pythonnet configuration
sys.path.append('./DotNET/')
import clr # Allow importing of .NET modules (import pythonnet)
clr.AddReference('System')
clr.AddReference('System.Speech')
clr.AddReference('System.Globalization')
import System
import System.Speech.Recog... |
import requests
import json
def check_rank(player, platform="steam"):
"""Gets the Rocket League stats and name and dp of a UserID
Args:
player (str): The UserID of the player we want to rank check
platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox'
Returns:
... |
import asyncio
import os
import os.path
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from contextlib import suppress
from typing import Any, Dict, List, Optional, Tuple, Union
import aiohttp
import portpicker
from loguru import logger
from sc2 import paths, wsl
from sc2.control... |
from webapp import app, db
from flask import render_template, flash, redirect, url_for, request
from webapp.forms import LoginForm, SettingsForm, GPIOTypesForm, GPIORulesForm
from flask_login import current_user, login_user, logout_user, login_required
from webapp.models import User, GlobalConf, GPIOTypes, GPIO_connec... |
from .p94_has_created import P94HasCreated
from dataclasses import dataclass
@dataclass
class P135CreatedType(P94HasCreated):
"""
Scope note:
This property identifies the instance of E55 Type, which is created in an instance of E83 Type Creation
Examples:
- The description of a new ribbon worm species by Bü... |
from setuptools import setup, find_packages
setup(
name='cspy',
version='0.1.0',
packages=find_packages(exclude=['examples']),
)
|
# This is based on the setup.py example at:
# https://github.com/pypa/sampleproject/blob/master/setup.py
from setuptools import setup
# To use a consistent encoding
import codecs
import os.path
long_description = """
virocon
=======
virocon is a software to compute environmental contours.
A longer description is ... |
import logging
from model.LineChecker import LineChecker
from service.filter_chain_service import load_line_checker_list
from service.list_reader_service import load_identifier_list_of_type
def add_sys_list_checker(list_filter):
checklist = load_identifier_list_of_type('package')
line_checker = LineChecker(m... |
"""Define a function overlapping() that takes two lists and
returns True if they have at least one member in common,
False otherwise. You may use your is_member() function,
or the in operator, but for the sake of the exercise,
you should (also) write it using two nested for-loops."""
def overlapping(lst1, lst2):
... |
import numpy as np
def get_ttl_channels(playlist):
''' Crawls through the playlist to assemble a list of all TTL channels
whose state is specified at some point. Returns a list of the format
['ttlA0', 'ttlA1', ...]
'''
ttls = []
for stage in playlist:
sequence = stage['sequence'... |
#!/usr/local/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from simtk.openmm.app import *
from .topology import Topology
from .calibration import SAMSCalibrationEngine
from .simulation import ConstantPHSimulation
from .driver import (
ForceFieldProtonDrive,
AmberProtonDrive,
... |
# SPDX-License-Identifier: MIT
# (c) 2019 The TJHSST Director 4.0 Development Team & Contributors
from django.apps import AppConfig
class SitesConfig(AppConfig):
name = "director.apps.sites"
def ready(self):
from . import signals # noqa # pylint: disable=unused-import,import-outside-toplevel
|
import json
import ast
from database.core import db
from modules.module_botname import Module_BotName
from log import log_modules
class Modules:
def __init__(self):
self._client = None
self._loaded_modules = {}
async def set_client(self, client):
if self._client is None:
... |
from msl.equipment.connection_sdk import ConnectionSDK
def test_parse_address():
p = ConnectionSDK.parse_address
for address in ['', 'SDK', 'sdk', 'SDK:', 'SDK::', 'COM2', 'ASRL7::INSTR',
'ASRL/dev/ttyS1', 'SOCKET::192.168.1.100::5000', 'Prologix::192.168.1.110::1234::6']:
assert... |
from typing import TypeVar
def double(x):
return x + x
assert double(3) == 6
assert double("abc") == "abcabc"
|
import sys, os
import numpy as np
import ephesus
from tdpy.util import summgene
import tdpy
def make_rflxmoon( \
# type of orbital architecture
## 'plan'
## 'bhol'
## 'planmoon'
## 'bholmoon'
typeobar='planmoon', \
):
... |
#!/usr/bin/python2.7
"""Simple Turtle Graphics"""
from turtle import *
color('green')
forward(150)
right(120)
forward(150)
right(120)
forward(150)
|
# -*- coding: utf-8 -*-
from odoo import fields, models
from odoo import api
from odoo.exceptions import ValidationError
import logging
import json
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = "res.users"
login_with_ts_pro = fields.Boolean(
"Login with tspro"
)
... |
import sys
import os
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
# sys.path.append('/m... |
from typing import Union
import numpy as np
def uniform_dist(low: Union[float, int], high: Union[float, int]):
"""Random data generator for the uniform distribution.
Args:
low (Union[float, int]): The minimum value that can be generated
high (Union[float, int]): The maximum value that can be g... |
from typing import Protocol
from stream.data import BufferData
class StreamingDevice(Protocol):
def get_buffer_data(self) -> BufferData:
...
|
import openstack.config
conn = openstack.connect(cloud="openstack")
print "Servers:"
print conn.list_servers()
print "Image ID:"
imageufcqx = conn.get_image("Ubuntu1604UFCQX")['id']
print imageufcqx
print "Flavor:"
flavorufcqx = conn.get_flavor("ufcquixada")['id'];
print flavorufcqx
print "Creating Server:"
serve... |
"""Test consumer/producer interaction on the wire"""
import random
import string
from unittest.mock import MagicMock, patch
import pytest
from src.clients import Producer
from src.middleware import JSONQueue, XMLQueue
TOPIC = "".join(random.sample(string.ascii_lowercase, 6))
def gen():
while True:
yiel... |
import random
import sys
from faker import Faker
# generates fake data
from bootstrap_table import db, User
def create_fake_users(n):
faker = Faker()
for i in range(n):
user = User(name=faker.name(),
age=random.randint(20, 80),
address=faker.address(... |
#!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import numpy as np
import scipy.io.wavfile
import torch
from scipy import signal
from main import Net, num_tags, prediction_to_str
from morse import ALPHABET, SAMPLE_FREQ, get_spectrogram
if __name__ == "__main__":
parser = argparse.Argument... |
from PIL import Image
from os import makedirs
minZ = 2
maxZ = 6
def saveTile(tile, z, x, y):
makedirs('../tiles/{z}/{x}'.format(x = x, z = z), exist_ok = True)
tile.resize((256, 256), resample=Image.LANCZOS).save('../tiles/{z}/{x}/{y}.png'.format(x = x, y = y, z = z), 'png')
# Save and further break down the... |
import os
import shutil
import os.path as path
from collections import OrderedDict as odict
from PIL import Image, ImageTk
import random
import numpy as np
import tkinter as t
import tkinter.filedialog as fd
att_dict = {'5_o_Clock_Shadow': 0, 'Arched_Eyebrows': 1, 'Attractive': 2,
'Bags_Under_Eyes': ... |
from torch.utils.data import DataLoader
import math
from sentence_transformers import SentenceTransformer, LoggingHandler, losses, models, util
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
from sentence_transformers.readers import InputExample
import logging
from datetime import datetime
im... |
"""Tiktalik Command Line Interface"""
import sys
import setuptools
try:
import tiktalik_cli
except ImportError:
print("error: tiktalik-cli requires Python 3.5 or greater.")
sys.exit(1)
LONG_DESC = open('README.md').read()
DOWNLOAD = "https://github.com/tiktalik-cloud/tiktalik-cli/archive/v1.9.3.2.tar.gz"
... |
#!/usr/bin/env python
from __future__ import print_function
import math
import re
import sqlite3 as sqlite
import sys
TABLE_QUERY = \
"""
SELECT name, sql
FROM sqlite_master
WHERE type='table'
ORDER BY name
"""
def msg(e):
print(e, file=sys.stderr)
def regex_match(expr, item):
re... |
#!/usr/bin/python
import numpy as np
#OVERALL NOTES - created during code development#
###DETERMINING QC CUTOFFS###
##noticed strong clustering behavior of samples with good QC values (high reads, low noise, high CS) when I made a 3D plot, wanted to use this to define the cutoff boundaries
##so I wrote a sort of... |
from Simulator import Simulator
from Simulator_old import Simulator_old
from EigenSolver import EigenSolver |
'''
@description 2019/09/15 12:38
'''
# 遍历字典
person = {"username": "zhiliao", "age": 18, "weight": 160, "height": 180, "address": "长沙"}
# 1.遍历字典中所有的key:使用keys方法,这个方法将所有的键以列表的方式返回。
# username age weight height address
for key in person.keys():
print(key, end=" ")
print("")
print('='*20)
# 2.遍历字典中所有的value:使用va... |
import requests
from cisco_support import utils
class PI:
__headers = None
__verify = None
__proxies = None
def __init__(self, key: str, secret: str, verify: bool = True, proxies: dict = None) -> None:
self.__verify = verify
self.__proxies = proxies
token = utils.getToken(ke... |
#-----------------------------------------------------
# Mimas: conference submission and review system
# (c) Allan Kelly 2016-2020 http://www.allankelly.net
# Licensed under MIT License, see LICENSE file
# -----------------------------------------------------
# Written so we can remove numpy from dependencies
def me... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
"""Prints inputs in sequence on standard output"""
def broken_pipe():
sys.stderr.close()
exit(0)
def dump(ifile):
n = 0
while True:
b = ifile.read(1)
if len(b) == 0:
break
... |
import unittest
from time import time
from pickle import load, dump
from tempfile import mkstemp
from random import choice, randint
from string import ascii_letters
from numpy import corrcoef, random, abs, max, asarray, round, zeros_like
from trlda.models import OnlineLDA
from trlda.utils import sample_dirichlet
from ... |
from pyopenproject.api_connection.exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.get_request import GetRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.help_texts.help_texts_comand import HelpTexts... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.