content stringlengths 5 1.05M |
|---|
#!/bin/env python3
# -*- coding: utf-8 -*-
import time
import datetime
import sys
# TODO: Create number converter method into graphics
# FIXME: this and that
for i in range(10):
timeticker = datetime.datetime.now().strftime("%H:%M:%S")
sys.stdout.write("\r{0}".format(timeticker))
sys.stdout.flush()
... |
import random
from random import randint
random.seed()
computer_choice = randint(1, 3)
user_choice = input("Rock Paper or Scissors? ").lower()
def game():
if computer_choice == 1 and user_choice == "rock":
print("Computer did: Rock")
print("Tie, Everybody Loses!")
elif computer_choice == 1 an... |
from __future__ import unicode_literals
import io
import logging
from django.utils.translation import ugettext_lazy as _
from acls import ModelPermission
from common import MayanAppConfig, menu_facet, menu_sidebar
from django_gpg.exceptions import GPGDecryptionError
from django_gpg.runtime import gpg
from documents.... |
import setuptools
import pgaudi
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pgaudi",
version="1.0.0",
description=pgaudi.__description__,
long_description=long_description,
author=pgaudi.__author__,
author_email="andresgineranton@outlook.com",
... |
from django.contrib import admin
# Register your models here.
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from radionator.profiles.models import Profile
RadioUser = get_user_model()
class ProfileInlineAdmin(admin.StackedInline):
"""This class includes the Prof... |
"""``pytest`` configuration."""
import pytest
import rasterio
from rasterio.env import GDALVersion
with rasterio.Env() as env:
drivers = env.drivers()
# Define helpers to skip tests based on GDAL version
gdal_version = GDALVersion.runtime()
requires_webp = pytest.mark.skipif(
"WEBP" not in drivers.keys(), ... |
from .test_case import TestCase, TemporaryBaseDirectoryTestCase
from infi.app_repo.config import Configuration, WebserverConfiguration, RPCServerConfiguration, FtpServerConfiguration
from infi.gevent_utils.os import path
import six
class GettersTestCase(TestCase):
def test_get_projectroot(self):
from infi... |
"""
Copyright (C) 2018-2020 Intel Corporation
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 i... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, erpnext
from frappe import _
from frappe.utils import flt
from frappe.model.meta import get_field_precision
from frappe.model.document import Doc... |
import tempfile
from pathlib import Path
import pytest
from ape.exceptions import ContractLogicError
from ape_ethereum.ecosystem import NETWORKS
from ape_hardhat.providers import HardhatForkProvider
TESTS_DIRECTORY = Path(__file__).parent
TEST_ADDRESS = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"
@pytest.fixture(... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# Based off: https://gist.github.com/kch42/565419/download
# NOTE FOR WINDOWS USERS:
# You can download a "exefied" version of this game at:
# http://kch42.de/progs/tetris_py_exefied.zip
# If a DLL is missing or something like this, write an E-Mail (kevin@kch42.de)
# or l... |
import sys
from itertools import combinations
_, m = list(map(int,sys.stdin.readline().strip('\n').rstrip().split(" ")))
cards = list(map(int,sys.stdin.readline().strip('\n').rstrip().split(" ")))
combo = list(combinations(cards,3))
sums = 1000000
for c in combo:
new_sum = sum(list(c))
if(new_sum <= m and (abs... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from pytdproxy import auth_pb2 as pytdproxy_dot_auth__pb2
class AuthServiceStub(object):
"""Missing associated documentation comment in .proto file."""
... |
#!/bin/env python
#==========================================================================
# (c) 2006 Total Phase, Inc.
#--------------------------------------------------------------------------
# Project : Aardvark Sample Code
# File : aabitrates.py
#------------------------------------------------------------... |
import requests
from flask import Flask, request
import flask_restful
from flask_restful import Resource, Api
import logging
from urllib.parse import urlparse
from functools import wraps
from flask_jwt_extended import JWTManager, create_access_token, get_jwt_identity, verify_jwt_in_request, decode_token
from flask_jwt_... |
from datetime import date
from controllers.c_employee import CEmployee
from exceptions.abort_exception import AbortException
from models import try_commit, AssessmentService, BOSType, CompanyTier, CompanyType, ExtraService, \
FinancialService, GeoZone, InstallConstructService, InsuranceService, InverterType, Logis... |
import subprocess, threading, time, importlib, sys, requests
import config
threads = []
def block_tup_to_class(tup):
block_module = importlib.import_module('commands.' + tup[0])
block = block_module.Block(tup[3])
block.type = tup[0]
block.icon = tup[1]
block.interval = tup[2]
return block
bl... |
# IMPORTS
import sys
from fasp.runner import FASPRunner
# The implementations we're using
from fasp.loc import DRSMetaResolver
from fasp.search import DiscoverySearchClient
from fasp.workflow import DNAStackWESClient
def main(argv):
faspRunner = FASPRunner(pauseSecs=0)
pp_dbgap_join = "SELECT sp.dbGaP_Subjec... |
import random
from collections import deque
class ReplayBuffer(object):
def __init__(self, capacity):
self.buffer = deque([], maxlen=capacity)
def push(self, item):
"""Save a transition"""
self.buffer.append(item)
def sample(self, batch_size):
return random.sample(self.bu... |
from typing import Set
import numpy as np
from obp import ope
from obp.ope import OffPolicyEvaluation
from obp.types import BanditFeedback
def test_fixture(
synthetic_bandit_feedback: BanditFeedback,
expected_reward_0: np.ndarray,
feedback_key_set: Set[str],
random_action_dist: np.ndarray,
) -> None... |
from networking.networking import * |
# -*- coding: utf-8 -*-
# the __all__ is generated
__all__ = []
# __init__.py structure:
# common code of the package
# export interface in __all__ which contains __all__ of its sub modules
# import all from submodule em_index_meta_recorder
from .em_index_meta_recorder import *
from .em_index_meta_recorder import __a... |
# compat3.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,W0122,W0613,W0706
###
# Function
###
def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
tr... |
from tokens import (
Token,
INTEGER, EOF,
LPAR, RPAR,
PLUS, MINUS,
MULTIPLY, DIVISION,
)
class Lexer(object):
def __init__(self, text):
# client string input, e.g. "4 + 2 * 3 - 6 / 2"
self.text = text
# self.pos is an index into self.text
self.pos = 0
s... |
"""
Parsers are used to parse the content of incoming HTTP requests.
They give us a generic way of being able to handle various media types
on the request, such as form content or json encoded data.
"""
from __future__ import unicode_literals
import codecs
from django.conf import settings
from django.core.files.uplo... |
# 3. Reporte de Inclusión Financiera, CNBV:
# a. Periodicidad: Trimestral
# b. Liga: https://www.cnbv.gob.mx/Inclusi%C3%B3n/Paginas/Bases-de-Datos.aspx
# Librerias
import csv
import xlrd
import requests
import os
import pandas as pd
import time
os.getcwd()
# Protocolo WEB para la conexion
import ... |
# 单调栈的应用
# easy
class Solution:
def dailyTemperatures(self, T):
mono_stack=[]
res=[0]*len(T)
for i in range(len(T)):
while mono_stack and T[i]>mono_stack[-1][0]:
res[mono_stack[-1][1]]=i-mono_stack[-1][1]
mono_stack.pop()
mono_stack.ap... |
#!/usr/bin/env python
# encoding: utf-8
"""
extract rst tests
"""
from __future__ import print_function
import os
import sys
import stat
import argparse
import re
capture_space = re.compile(r"(\s*)\S.*")
capture_chapter = re.compile(r"\s*.. _Chapter-([a-zA-Z0-9._-]+):\s*")
capture_testname = re.compile(r"\s*[*]?Ex... |
from django.contrib.auth import login
from django.shortcuts import render
from django.views import View
import re
from users.models import User
from django.db import DatabaseError
from django.shortcuts import redirect
from django.urls import reverse
class RegisterView(View):
"""用户注册"""
def get(self, request... |
import sys
import traceback
from contextlib import contextmanager
import six
@contextmanager
def tee_output(stream):
"""Tee stdout and stderr to an additional (combined) output stream
:param stream: File-like object open for writing or file path (str)
or `None`. A value of `None` or empty string will cr... |
import unittest
import base64
import encryption
import settings
class TestEncryption(unittest.TestCase):
def setUp(self):
self.test_folder = "test_folder"
self.test_file = "{}/test.txt".format(self.test_folder)
self.test_file_encrypted = self.test_file + settings.ENCRYPTED_FILE_EXTENSION... |
#! /bin/bash env python
import sys,time
import numpy as np, math
import itertools
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from tqdm import tqdm
class Calc:
def __init__(self,*args):
self._args = args
def args(self):
return self._args
def points_check(sel... |
# Copyright 2020 Hamal, Inc.
from __future__ import division
import base64
import time
import calendar
from dateutil import tz
from datetime import datetime
from oslo_log import log as logging
from hamal.openstack.instance import Instance
from hamal.plugin.openstack import OpenstackPlugin
class ViewBuilder(object)... |
class BinException(Exception):
pass |
"""Top-level package for Large Image Tasks."""
__author__ = """Kitware Inc"""
__email__ = 'kitware@kitware.com'
from girder_worker import GirderWorkerPluginABC
try:
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _importlib_version
except ImportError:
from i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-26 16:26
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... |
import pytest
def pytest_addoption(parser):
parser.addoption('--interface', action='store')
@pytest.fixture(scope='session')
def opt(request):
opt = {'interface': request.config.getoption("--interface")}
return opt
|
# Main imports
import os
from flask import current_app as app
from flask import request, redirect, render_template, url_for, Response
# Markdown imports
from markdown import markdown as markd
import markdown.extensions.fenced_code
import markdown.extensions.codehilite
from pygments.formatters import HtmlFormatter
# App... |
# -*- coding: utf-8 -*-
#
#
import sys
import unittest
import warnings
sys.path.insert(0, '../..')
from ansible_api.ansible.inventory import BaseInventory
warnings.simplefilter("ignore", ResourceWarning)
class TestJMSInventory(unittest.TestCase):
def setUp(self):
host_list = [{
"hostname": "... |
import dgl
from dgl.data import DGLDataset
from dgl import data
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import dgl.function as fn
from dgl.nn.pytorch import edge_softmax, GraphConv
gcn_msg = fn.copy_src(src='h', out='m')
gcn_reduce = fn.sum(msg='m', out='h')
c... |
from context import motivatemebot as mmb
if __name__ == '__main__':
img = mmb.get_image('../images/flowers.jpg')
# img = mmb.get_image('../images/elizabeth_lab.jpg')
# img = mmb.get_image('../images/chris.jpg')
# img = mmb.get_image('../images/github_page.jpg')
location, color = mmb.select_region_... |
import json
import urllib.request
from collections import defaultdict
from datetime import datetime
def calculate_match_points(team1, team2, score1, score2):
if score1 == score2:
return {team1: 1, team2: 1}
elif score1 > score2:
return {team1: 3, team2: 0}
else:
return {team1: 0, t... |
import itertools
from day5 import parse
from intcode import IntCode
class Amplifier(IntCode):
pass
def permutations(L):
"""permutation implementation, just for fun
should be the same as itertool.permutations
"""
if not L:
return [()]
ans = []
for i, item in enumerate(L):
... |
"""
Example of running PyTorch implementation of DDPG on HalfCheetah.
"""
import sys
sys.path.append('../')
import copy
from rlkit.torch.ddpg.dsfpg import DSFPGTrainer
from gym.envs.mujoco import HopperEnv
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.envs.wrappers import NormalizedBox... |
from django.urls import path
from DBStorage.views import ParticipantView, CollectionAnswersView, GiftAnswersView, GiftParticipantView, StorageSettingsView
urlpatterns = [
path('Storage/', StorageSettingsView.as_view(), name='storagesettingsview'),
path('Collection/<str:caID>', CollectionAnswersView.as_view(),... |
import time
from image_app_core import start_server_process, get_control_instruction, put_output_image
import cv2
import os
import camera_stream
from pid_controller import PIController
from robot import Robot
class FaceTrackBehavior:
"""Behavior to find and point at a face."""
def __init__(self, robot):
... |
from func import *
me='deepinmylife'
api=auth(me)
it=0
for i in tweepy.Cursor(api.friends, id=me).items():
it+=1
if it%50==0:
api=auth(me)
api.destroy_friendship(i.screen_name)
print('Unfollow. {}.'.format(it),i.screen_name)
time.sleep(5) |
import psycopg2
from psycopg2 import sql, extras
# If there is no venv, run schrodinger_virtualenv.py schrodinger.ve to install pycopg2
# In win powershell as admin:
# >Set-Location -Path "C:\Program Files\Schrodinger2020-3"
# >Set-ExecutionPolicy RemoteSigned
# >schrodinger.ve\Scripts\activate
# or source... |
from admit.AT import AT
class ContinuumMap_AT(AT):
def __init__(self):
AT.__init__(self)
|
from IrohaUtils import *
import logging
import hashlib
import threading
class BlockStorehouse():
"""
A class to track the blocks being placed on the chain, to cache the results of querying blocks
This will allow for a speed up as we will not need to query the same low height blocks over and over
"""
... |
class ExternalResourceUtils(object):
""" A utility class containing functions related to external resource references. """
@staticmethod
def GetAllExternalResourceReferences(document,resourceType=None):
"""
GetAllExternalResourceReferences(document: Document) -> ISet[ElementId]
Gets the ids of all... |
import multiprocessing
import time
g_var=100
def add():
global g_var
for i in range(5):
g_var+=1
print('the value in add is %d'%(g_var))
def get():
global g_var
print('the value in get is %d'%(g_var))
p1 = multiprocessing.Process(target=add)
p1.start()
time.sleep(1)
p2 = multiproce... |
import copy
import logging
import os
import time
import librosa
from tensorboardX import SummaryWriter
from torch.autograd import Variable
from torch.optim import lr_scheduler
from audio_utils import *
from utils import Profiler, prepare_spec_image
'''
TODO: decide whether to retrieve net1_model from outside of the ... |
"""
============================================================
Dijkstra algorithm for finding single-source shortest path
============================================================
Given a directed graph and a source vertex in the graph,
the task is to find the shortest distance and path from source to target ... |
#!/usr/bin/env python
import os
import gym
from util import Trainer
env = gym.make("rangl:nztc-open-loop-v0")
# Train an RL agent on the environment
trainer = Trainer(env)
os.chdir("./saved_models/")
trainer.train_rl(models_to_train=1, episodes_per_model=100)
os.rename("MODEL_0.zip", "MODEL_open_loop_0.zip")
os.chd... |
from http.server import HTTPServer as _HTTPServer
from socketserver import ThreadingMixIn as _ThreadingMixIn
class ThreadingHTTPServer(_ThreadingMixIn, _HTTPServer):
'''Multi-threaded HTTPServer'''
pass
|
from pexpect import pxssh
class Bot:
# initializing a new client bot
def __init__(self, host, user, password):
self.host = host # IP of bot host
self.user = user
self.password = password
self.session = self.ssh()
# SSH for client
def ssh(self):
try:
... |
import time
import pathlib
import logging
def get_logger(name: str = "project", level: str = "info") -> logging.Logger:
# set logger
logger = logging.getLogger(name)
level_dict = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ER... |
from ucate.application.workflows.tarnet import train as train_tarnet
from ucate.application.workflows.tlearner import train as train_tlearner
from ucate.application.workflows.cevae import train as train_cevae
from ucate.application.workflows.evaluation import evaluate
from ucate.application.workflows.evaluation impo... |
from __future__ import annotations
from typing import (Any, Dict, Literal, Mapping, Optional, Type, TypeVar,
overload)
from ._base import BaseComponent
from ._internal_namespace import register_component, register_library_class
from .errors import (CommandAlreayExistsError, CommandNotExistError,
... |
import argparse
import numpy as np
import tensorflow as tf
from sensortransformer import set_network
from data import load_data
parser = argparse.ArgumentParser()
parser.add_argument("--signal-length", type=int)
parser.add_argument("--segment-size", type=int)
parser.add_argument("--num_channels", type=int)
parser.add_... |
from unittest.mock import Mock, patch
from hammurabi.exceptions import NotificationSendError
from hammurabi.notifications.slack import SlackNotification
@patch("hammurabi.notifications.slack.Slack")
def test_send_notification(mock_client_class):
mock_client = Mock()
mock_client_class.return_value = mock_clie... |
import serial
class SerialController:
def __init__(self):
self.__correctionKey = {
"Actylene": 0.58, "Air": 1.00, "Ammonia": 0.73,
"Argon": 1.39, "Arsine": 0.67, "Boron Trichloride": 0.41,
"Bromine": 0.81, "Carbon Dioxide": 0.70,
"Carbon Monoxide"... |
from django.conf.urls import include, url
from rest_framework import routers
from gwaithdemo import views
router = routers.DefaultRouter()
router.register(r'rates', views.RateViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
|
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from django.core import signals
from django.db import connections
from catcher.models import Callback, Fingerprint, Token
from catcher.settings import TOKEN_Q... |
# author: Milinda Fernando
# simple paraview python script to bh binary visualization problem ().
# School of Computing, University of Utah
# 12/12/2017
import argparse
import resource
import gc
#from pympler.tracker import SummaryTracker
# import the simple module from the paraview
from paraview.simple import *
#impor... |
import pickle
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.applications.inception_v3 import InceptionV3
from keras.models import Model, Sequential
from keras.layers import Input, GlobalMaxPooling2D, AveragePooling2D, ZeroPadding2D, add, concatenate, Dense, Dropout, Activation, Fl... |
from random import randint
import pygame
from pygame.sprite import Sprite
class Ball(Sprite):
"""A class to represent a ball."""
def __init__(self, settings, screen):
"""Initialize the ball and set its starting position."""
self.screen = screen
self.settings = settings
... |
"""
Support Vector Regression test on roles.salaries data.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
df = pd.read_csv('./../../data/roles.salaries.csv')
X = df.iloc[:, 1:2].values
y = df.iloc[:, 2].values
prin... |
import endpoints
from config import CLIENT_IDS, AUDIENCES
api = endpoints.api(name='roadkills', version='v1',
allowed_client_ids=CLIENT_IDS,
audiences=AUDIENCES)
|
""" microstructure data output """
import h5py
import numpy as np
from . import io
stats_df = None # pandas dataframe for stats output
unique_ids = None # list of Potts states
output_index = 0
stats_file = None
def initialize(sites, args):
global unique_ids
global stats_file
stats_file = args.statsfile
num... |
#!/usr/bin/env python
# Copyright 2015 Quantopian, Inc.
#
# 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 ... |
import json
myxopath = "dzf1_parsed.json"
with open(myxopath, "r") as file:
myxodb = json.load(file)
for gene in myxodb[0]:
name = gene['name']
updated = name + " " + gene['locus_tag']
gene['symbol'] = updated[0].lower() + updated[1:]
gene['name'] = updated[0].upper() + updated[1:]
with open(myx... |
import stk
def test_initialization():
for i in range(1, 119):
a1 = stk.Atom(
id=1,
atomic_number=i,
attr1=12,
attr2='hi',
_private_attr=123
)
a2 = stk.Atom._elements[i](2, -3, attr3='bye', attr4=321.12)
assert a1.__class_... |
from __future__ import unicode_literals
from .abc import Writer
import cgi
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
attribute_string = _gen... |
import cv2
import numpy as np
class Filter(object):
'''calc local binary pattern'''
def __init__(self, params):
self.params = params
self.lbp_type = params[0]
def apply(self, img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
pad = np.pad(gray, [1, 1], 'const... |
#encode: utf-8
import os
import skimage.io
import matplotlib.pyplot as plt
def getImagePathsFromDir(imgDir):
"""
Function: Get paths of all images from the input directory
Input:
imgDir: the input directory
Output:
path_list: a list of path
Date: 2018.04.09
Author: Jie Lyu
... |
__author__ = 'topcircler'
import endpoints
from api.vote_api import VoteApi
from api.anno_api import AnnoApi
from api.flag_api import FlagApi
from api.followup_api import FollowupApi
from api.user_api import UserApi
from api.account_api import AccountApi
from api.util_api import UtilApi
from api.community_api import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `certifiable.core.certify_bytes` method."""
import unittest
from decimal import Decimal
import six
from certifiable import CertifierTypeError, CertifierValueError
from certifiable.core import certify_bytes
class CoreCertifyBytesTestCase(unittest.TestCase)... |
#Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-las, sabendo que cada litro de tinta pinta uma área de 2m^2
altura = float(input('Qual a altura da parede: '))
largura = float(input('Qual a largura da parede: '))
area = largura *... |
from datetime import datetime
import itertools
import logging
import z3
import utils
from utils import MySet
import logic
from logic import Solver, Diagram, Trace, KEY_ONE, KEY_NEW, KEY_OLD, Blocked, CexFound
import phases
import syntax
from syntax import Expr, AutomatonDecl
import pickle
from typing import List, Opti... |
import six
from django.core.cache import InvalidCacheBackendError
from djedi.utils.encoding import smart_str, smart_unicode
from cio.backends.base import CacheBackend
from django.core.cache.backends.locmem import LocMemCache
from djedi.compat import get_cache
class DjangoCacheBackend(CacheBackend):
def __init__... |
# -------------------------------------------------------------
#
# Climbable object
#
# The climbable object works so that once climbed, it sets
# a flag on the climber to show that it was climbed. A simple
# command 'climb' handles the actual climbing. The memory
# of what was last climbed is used in a simple puzzle ... |
from django.apps import AppConfig
class EkohmsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ekohms'
|
from pika import BlockingConnection
from pika import URLParameters
from sdc.rabbit.publishers import QueuePublisher, PublishMessageError
def reprocess():
# To use this script, fill in the credentials for rabbit. They should be found in app/settings.py
rabbit_url = 'amqp://<user>:<pass>@<host>:<port>/%2f'
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# """
# - Author: steve simmert
# - Copyright: 2017
# """
# Model function of IRM intensity profile of a tilted MT and TIRF intensity profile
from scipy import sin, cos, arcsin, pi, sinc
def height_fun(x, x0, A, xt):
"""
Model the height of a cantilevered microub... |
"""https://code.google.com/codejam/contest/4344486/dashboard#s=p1"""
import sys
INPUT = "B-large-practice.in"
# INPUT = "B-small-practice.in"
# INPUT = None
def main():
T = int(input())
for i in range(1, T + 1):
N = int(input())
mat = []
for _ in range(N):
mat.append([s =... |
from distutils.core import setup
setup(
name = 'cluster_submission',
version = '1.0',
py_modules = ['cluster_submission'],
packages = ['portalocker'],
description = 'Tool to automate submission of jobs to computer clusters',
long_description =
'''
Cluster Submission is a tool I made to... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
class Token:
"""
Base class for tokens, the atomic units of recognizable text in a stream
"""
# constants; set at compile time
name = '' # the name of the token
head = '' # a pattern for text ... |
# -*- coding: utf-8 -*-
# @Time : 2017/12/21 下午3:11
# @Author : Mazy
# @File : html_parser.py
# @Software: PyCharm
import re
from TieBa_spider import tools
class HtmlParser(object):
def __init__(self):
self.tool = tools.Tool()
def parser(self, html_content):
title = self.get_title(htm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Rockson Chang
"""
# setup.py
from setuptools import setup, find_packages
REQUIRED_PACKAGES = [
'pyYaml>=3.12',
'keras==2.0.6', # was crashing on ml-engine for keras>=2.0
'matplotlib',
... |
##
# @brief A class to hold actor movie data -- using IMDB dataset
#
#
# @author Kalpathi Subramanian
# @date 2/18/18
#
#
class ActorMovieIMDB():
##
# This method initializes an actor movie object with an actor/movie pair.
#
# @param a - actor (string)
# @param m - movie (string)
# @param r - rating (... |
import importlib
import socket
from threading import Thread
from wsgiref.simple_server import make_server
try:
from urllib.request import urlopen
except ImportError: # python2
from urllib import urlopen
class Server:
def __init__(self, conf):
self.conf = conf
self.thread = Thread(target=s... |
#!/usr/bin/python3
from botbase import *
import re, time
_csvbreak = re.compile(r"\r?\n(?:;{10,}\r?\n)+",re.M)
_sanhalt = re.compile(r"verbraucherschutz.sachsen-anhalt.de").search
def sanhalt(sheets):
import pandas, io, dateparser
data = get_raw("https://lavst.azurewebsites.net/Corona/Verlauf/COVID19_Aktuell_... |
"""NGPVAN Activist Code Endpoints"""
from parsons.etl.table import Table
from parsons.ngpvan.utilities import action_parse
import logging
logger = logging.getLogger(__name__)
class ActivistCodes(object):
def __init__(self, van_connection):
self.connection = van_connection
def get_activist_codes(s... |
from database import Base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, String, Integer, Date, ForeignKey, Numeric, DateTime
class Loja(Base):
'''
CLASSE LOJA - MAPEIA TABELA TLoja NO BANCO DE DADOS
@autor: Gabriel Oliveira Gonçalves -
@data: 29/08/2020 -
@versao... |
from flask import current_app
from flask_login import UserMixin
from werkzeug.security import check_password_hash, generate_password_hash
from .. import db, login_manager
class Permission:
GENERAL = 0x01
ADMINISTER = 0xff
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary... |
#!/usr/bin/env python
#
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#
from simpleeval import EvalWithCompoundTypes
from capdl.Object import register_object_sizes, Untyped
from capdl.Allocator import ASIDTableAllocator, BestFitAllocator
from capdl import ELF, lookup_ar... |
"""
Build Robot
"""
from abc import abstractmethod, ABC
class Robot:
"""
Characteristics of Robot
"""
def __init__(self, robot_name: str) -> None:
self.label: str = robot_name
self.is_bi_pedal: bool = False
self.is_quad_pedal: bool = False
self.is_wheeled: bool = False... |
'''
Plot functions to graphically present simulation results
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from parameters import SAVE_FIGS, ONE_FIGURE
server_names = ['server 1', 'server 2', 'server 3',
'server 4', 'server 5']
color_sequence = ['#1f77b4', '#aec7e8', '#ff7... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.