text stringlengths 2 999k |
|---|
# This is an example of firing up PyMOL inside of a subordinate
# process via an "import pymol"
#
# NOTE: for this to work, PyMOL must be installed in a
# Python-dependent fashion (e.g. pymol-0_98-bin-win32-py23) etc.
#
# WARNING: stability issues have been known to occur with this
# approach, so anticipate problems..... |
import unittest
def linear_sum(S, n):
"""Return the sum of the first n numbers of sequence S."""
if n == 0:
return 0
else:
return linear_sum(S, n - 1) + S[n - 1]
class TestLinearSum(unittest.TestCase):
def test_linear_sum(self):
S = [4, 3, 6, 2, 8]
self.assertEqual(23,... |
from django.urls import path
from . import views
#here are our app-connections.(these connection just affect to our app, not at entire system)
#each connection going us to a view functionality
#these connections needs to be connect with url root, because that's where the requests come from
app_name = 'polls'
urlpat... |
"""
Menu handling file
- Every menu is of the Menu class
- Menus are initialized with an array of options
- What a menu option does is determined by the following table:
- "set_state_map": s.set_state('map')
- "exit": exit()
"""
from config import *
import sys
class Menu:
def __init__(self, options, sel_inde... |
# -----------------------------------------------------------------------------
# ply: yacc.py
#
# Copyright (C) 2001-2011,
# David M. Beazley (Dabeaz LLC)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
from enum import Enum
class GameScenes(Enum):
FIRST_LEVEL = 1
SECOND_LEVEL = 2
THIRD_LEVEL = 3
FOURTH_LEVEL = 4
FIFTH_LEVEL = 5
|
"""
login app
"""
from zoom.apps import App
class MyApp(App):
pass
app = MyApp()
|
from cohere import Diffractometer
class Diffractometer_34idc(Diffractometer):
"""
Subclass of Diffractometer. Encapsulates "34idc" diffractometer.
"""
name = "34idc"
sampleaxes = ('y+', 'z-', 'y+') # in xrayutilities notation
detectoraxes = ('y+', 'x-')
incidentaxis = (0, 0, 1)
sample... |
# 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... |
# -*- coding: utf-8 -*-
"""
Statement pre-processors.
"""
def clean_whitespace(chatbot, statement):
"""
Remove any consecutive whitespace characters from the statement text.
"""
import re
# Replace linebreaks and tabs with spaces
statement.text = statement.text.replace('\n', ' ').replace('\r'... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import sys
class NaluWind(CMakePackage):
"""Nalu-Wind: Wind energy focused variant of Nalu."""
... |
sentence = input().split()
ae = 0
for word in sentence:
if 'ae' in word:
ae += 1
if ae/len(sentence) >= 0.4:
print("dae ae ju traeligt va")
else:
print("haer talar vi rikssvenska") |
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import with_metaclass, viewkeys, PY3
import types
try:
from collections import OrderedDict
except ImportError:
from pip._vendor.ordereddict import OrderedDict
from . import _inputstream
from . import _tokenizer
from . im... |
from docutils.parsers.rst import roles
from docutils import nodes
from docutils.parsers.rst.states import Inliner
import docutils.parsers.rst.roles
def strike_role(role, rawtext, text, lineno, inliner: Inliner, options={}, content=[]):
"""
USAGE: :del:`your context`
:param role: my-strike
:param raw... |
print("Hello Github!")
|
# Author: Khalid - naam toh suna hi hoga
# Steps to run ->
# :~$ python yoyo.py
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template("my-form.html")
@app.route('/', methods=['POST'])... |
# Copyright 2019 Ram Rachum and collaborators.
# This program is distributed under the MIT license.
import io
import textwrap
import threading
import types
import sys
from pysnooper.utils import truncate
from python_toolbox import sys_tools, temp_file_tools
import pytest
import pysnooper
from pysnooper.variables imp... |
import logging
import pathlib
from unittest import mock
from cabinetry import templates
@mock.patch("cabinetry.route.apply_to_all_templates")
@mock.patch("cabinetry.templates.builder._Builder")
def test_build(mock_builder, mock_apply):
config = {"General": {"HistogramFolder": "path/", "InputPath": "file.root"}}
... |
from flask import Blueprint, jsonify
from flask import request
from flask import abort
from services.fault_injector import FaultInjector
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from ser... |
#!/usr/bin/env python
import socket
import re
class RobotFeedback:
"""Class for the Mecademic Robot allowing for live positional
feedback of the Mecademic Robot.
Attributes
----------
address : string
The IP address associated to the Mecademic robot.
socket : socket
Socket con... |
"""
Regression tests for Model inheritance behavior.
"""
from __future__ import unicode_literals
import datetime
from operator import attrgetter
from unittest import expectedFailure
from django import forms
from django.test import TestCase
from .models import (
ArticleWithAuthor, BachelorParty, BirthdayParty, Bu... |
import os
# import torch
import argparse
import base64
import sys
import io
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
def fullmodel2base64(model):
buffer = io.BytesIO()
torch.save(mode... |
#Question No 6
#Risen Each Year For Next 25 Years
year =1
millimeter= 1.6
while(year<=25):
years=(year * millimeter)
print(" The ocean will rises each year is=" , years,)
year+=1 |
from fastapi import FastAPI
import uvicorn
from src.routes import (
user,
employee,
car,
inventory,
product,
service,
dealership,
department,
)
from fastapi.middleware.cors import CORSMiddleware
from src.settings.envvariables import Settings
Settings().check_variables()
app = FastAPI()... |
from django.db.models import Q
from apps.configattribute.models import ConfigAttribute
from apps.property.models import GenericProperty
from apps.utils.data_helpers.manager import DataManager
from apps.utils.iotile.variable import SYSTEM_VID
from apps.utils.timezone_utils import display_formatted_ts
class TripInfo(o... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
"""
:author: Thomas Delaet <thomas@delaet.org>
"""
from velbus.modules.vmb4ry import VMB4RYModule
from velbus.modules.vmbin import VMB6INModule
from velbus.modules.vmbin import VMB7INModule
|
from unittest.mock import MagicMock
from django.urls import reverse
from hijack.contrib.admin import HijackUserAdminMixin
from hijack.tests.test_app.models import Post
class TestHijackUserAdminMixin:
def test_user_admin(self, admin_client):
url = reverse("admin:test_app_customuser_changelist")
r... |
"""
Django settings for modelpractice project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import... |
import os
import numpy as np
import pandas as pd
import binascii
import warnings
import tempfile
from math import ceil
from multiprocessing import cpu_count, sharedctypes
from multiprocessing.pool import Pool
from sklearn.metrics import r2_score
from deepimpute.net import Net
from deepimpute.normalizer import Normaliz... |
# -*- coding: utf-8 -*-
""" Command line configuration parser """
import sys
import os.path
import argparse
import configparser
def parse():
""" Parse command line options """
parser = argparse.ArgumentParser(
description='Dynamic DynamoDB - Auto provisioning AWS DynamoDB')
parser.add_argument(
... |
# -*- coding: utf-8 -*-
from requests import Session
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError
import json
from time import sleep, time
from pprint import pprint
from itertools import cycle
from .storage import nodes, api_total
#from .proxy import Proxy
class Http():
... |
import json
import pathlib
import sys
import time
from typing import Sequence
import bentoml
from bentoml.adapters import (
DataframeInput,
FileInput,
ImageInput,
JsonInput,
MultiImageInput,
)
from bentoml.frameworks.sklearn import SklearnModelArtifact
from bentoml.handlers import DataframeHandler ... |
from PIL import Image
images = []
for i in range(9):
images.append(Image.open(f"../examples/lf/results/render_0{i}_{i}.0.png"))
images[0].save("../examples/lf/out.gif", save_all=True, append_images=images[1:], duration=100, loop=0) |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils import FieldTracker
from waldur_core.core import models as core_models
from waldur_core.structure import models as structure_models
class VirtualMachineMixin(models.Model):
class Meta:
abstract = True
... |
# -*- coding: utf-8 -*-
# Meta
__version__ = "0.0.4"
__author__ = 'Rhys Elsmore'
__email__ = 'me@rhys.io'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2014 Rhys Elsmore'
# Module Namespace
from .core import MetricsLogger, GroupMetricsLogger
from .api import timer, increment, sample, measure, unique, group
... |
## Copyright 2019 The Rules Protobuf 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 require... |
# 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... |
import json
from rest_framework.test import APITestCase
from django.urls import reverse
from rest_framework import status
from django.contrib.auth import get_user_model
from authors.apps.articles.models import Articles
from authors.apps.profiles.models import Profile
class TestGetEndpoint(APITestCase):
def set... |
from abc import ABCMeta, abstractmethod
from frozendict import frozendict
class ResourceManager(metaclass=ABCMeta):
def __init__(self):
self.wv_filename = ""
self.parsed_filename = ""
@abstractmethod
def write(self):
"""
parse the raw file/files and write the data to disk... |
import torch.utils.data as data
import os
import os.path
from numpy.random import randint
from ops.io import load_proposal_file
from transforms import *
from ops.utils import temporal_iou
class SSNInstance:
def __init__(
self,
start_frame,
end_frame,
video_frame_count,
fps... |
from .routes import app as websockets_routes
|
import json
from server import db
from sqlalchemy.ext import mutable
class JsonEncodedDict(db.TypeDecorator):
impl = db.Text
def process_bind_param(self, value, dialect):
if value is None:
return '{}'
else:
return json.dumps(value)
def process_result_value(self, val... |
import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from cgatReport.Tracker import *
from cpgReport import *
##########################################################################
class replica... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-07-04 00:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('library', '0001_initial'),
]
operations = [
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
ROOT_URLCONF = 'django_autoconfig.autourlconf'
INSTALLED_APPS = [
'django.contrib.auth',
'nuit',
]
STATIC_URL = '/static/'
STATIC_ROOT = '.static'
from django_autoconfig.autoconfig import configure_settings
configure_setting... |
"""
Django settings for my_blog project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
#... |
"""
Logic for uploading to s3 based on supplied template file and s3 bucket
"""
# Copyright 2012-2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License i... |
from model import common
import torch.nn as nn
import torch.nn.init as init
url = {
'r20f64': ''
}
def make_model(args, parent=False):
return VDSR(args)
class VDSR(nn.Module):
def __init__(self, args, conv=common.default_conv):
super(VDSR, self).__init__()
n_resblocks = args.n_resblocks... |
import PIL.Image
import PIL.ImageColor
import PIL.ImageEnhance
import zeit.cms.repository.folder
import zeit.connector.interfaces
import zeit.content.image.interfaces
import zope.app.appsetup.product
import zope.component
import zope.interface
import zope.security.proxy
class ImageTransform(object):
zope.interfa... |
#
# 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 your option) any later version.
#
# Written (C) 2012-2013 Heiko Strathmann
#
from numpy import *
from py... |
#
# Tests for current input functions
#
import pybamm
import numbers
import unittest
import numpy as np
class TestCurrentFunctions(unittest.TestCase):
def test_constant_current(self):
# test simplify
current = pybamm.electrical_parameters.current_with_time
parameter_values = pybamm.Paramet... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from moler.cmd.unix.ps import Ps
from moler.observable_connection import ObservableConnection, get_connection
from moler.io.raw.terminal import ThreadedTerminal
# v.1 - combine all manually
# moler_conn = ObservableConnection()
# terminal = ThreadedTerminal(moler_connection=moler_conn)
# v.2 - let factory combine
term... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0xde71c936
# Compiled with Coconut version 2.0.0-a_dev33 [How Not to Be Seen]
# Coconut Header: -------------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
import sy... |
import sys
import os
import copy
import json
import datetime
opt = dict()
opt['dataset'] = '../data/citeseer'
opt['hidden_dim'] = 16
opt['input_dropout'] = 0.5
opt['dropout'] = 0
opt['optimizer'] = 'adam'
opt['lr'] = 0.01
opt['decay'] = 5e-4
opt['self_link_weight'] = 1.0
opt['pre_epoch'] = 2000
opt['epoch'] = 100
opt... |
"""
Copyright (c) 2016, Jose Dolz .All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the f... |
from numbers import Number
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import math as m
from scipy.stats import norm
"""
Minigolf task.
References
----------
- Penner, A. R. "The physics of putting." Canadian Journal of Physics 80.2 (2002): 83-96.
"""
class MiniGolf(gym.Env)... |
class UnoInfo:
def __init__(self):
self.dataPins = 13
self.analogInPins = 5
self.GND = 3
self.pow = [3.3, 5]
self.TX = 1
self.RX = 0
def getMainInfo(self):
return {"0": self.dataPins, "1": self.GND, "2": self.pow}
def getDigitalPins(s... |
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import json
import random
import math
import time
import ssl
config_mqtt_broker_ip = "iot.fh-muenster.de"
config_mqtt_client_id = "dummy-receiver-" + str(random.randint(1000, 9999));
config_mqtt_topic = "sensor/60:01:94:4A:AF:7A"
ts_last_message = int(round(... |
# Online References used :
# https://github.com/imadmali/movie-scraper/blob/master/MojoLinkExtract.py
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/
# https://nycdatascience.com/blog/student-works/scraping-box-office-mojo/
# https://www.youtube.com/watch?v=XQgXKtPSzUI
# https://www.youtube.com/watch?v=aIPqt-... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
class PyPyqt5(SIPPackage):
"""PyQt is a set of Python v2 and v3 bindings for The Qt Co... |
AUTHPLUGIN_FIXTURE = '{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1alpha1","spec":{},"status":{"token":"test"}}'
|
import sqlite3
from flask import Flask, jsonify, request
app = Flask(__name__)
app.debug = True
api_key = "RANDOM ACCESS KEY HERE"
def CheckAPIKey(key):
if key == api_key:
return True
else:
return False
@app.route('/')
def HomeDir():
return jsonify({'msg': "invalid_endpoi... |
import os
import shutil
import subprocess
from pathlib import Path
from dotenv import dotenv_values
COMPOSAPY_ROOT_DIR = Path(__file__).parent
COMP_APP_PROD_DIR = COMPOSAPY_ROOT_DIR.parent.parent.joinpath("Product")
DATALAB_SERVICE_STATIC_DIR = COMP_APP_PROD_DIR.joinpath(
"CompAnalytics.DataLabService", "static"
)... |
"""
Ridge regression
----------------
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
from IPython.display import display
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from linregress import lr
# More on theory: https://en.wikip... |
from sympy import Symbol, gamma, oo, nan, zoo, factorial, sqrt, Rational, log,\
polygamma, EulerGamma, pi, uppergamma, S, expand_func, loggamma, sin, cos, \
O, cancel
x = Symbol('x')
y = Symbol('y')
n = Symbol('n', integer=True)
def test_gamma():
assert gamma(nan) == nan
assert gamma(oo) == oo... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict
import re
import string
from jina.hub.crafters.nlp.Sentencizer import Sentencizer
import pickle
# class Splitter(Sentencizer):
# count = 0
# separator = "|"
#
# def __init__(self,... |
import os
import os.path
import requests
import time
from pathlib import Path
from talon import ctrl, ui, Module, Context, actions, clip
import tempfile
# Courtesy of https://github.com/anonfunc/talon-user/blob/master/apps/jetbrains.py
extendCommands = []
# Each IDE gets its own port, as otherwise you wouldn't be ab... |
"""
2D Distributions
================
Some plots visualize a transformation of the original data set. Use a
stat parameter to choose a common transformation to visualize.
Each stat creates additional variables to map aesthetics to. These
variables use a common ..name.. syntax.
Look at the examples... |
from dataclasses import replace
from dataclass_abc import dataclass_abc
from rxbp.indexed.indexedflowable import IndexedFlowable
from rxbp.indexed.indexedsharedflowable import IndexedSharedFlowable
from rxbp.indexed.mixins.indexedflowablemixin import IndexedFlowableMixin
from rxbp.typing import ValueType
@dataclass... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#@title Input protein sequence(s), then hit `Runtime` -> `Run all`
#from google.colab import files
import os.path
import re
import hashlib
import random
def add_hash(x,y):
return x+"_"+hashlib.sha1(y.encode()).hexdigest()[:5]
with open("protein") as f:
query_... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
default_app_config = "grandchallenge.evaluation.apps.EvaluationConfig"
|
class StoryPytestError(Exception):
"""Base error of all stories-pytest errors."""
pass
|
from datetime import datetime
import re
from urllib.parse import quote
from django.db import models
from django.utils.html import urlize
from django.utils.timezone import make_aware, utc
from django.utils.translation import ugettext_lazy as _
from requests_oauthlib import OAuth1
import requests
from mezzanine.conf i... |
"""carfinder URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
from rest_framework.views import APIView
from knox.auth import TokenAuthentication
from rest_framework.permissions import IsAdminUser, IsAuthenticated, AllowAny
from rest_framework.response import Response
from jaseci.utils.utils import logger
from jaseci.api.public_api import public_api
from jaseci.element.element imp... |
from twisted.internet import reactor
from twisted.web import client, error, http
from twisted.web.resource import Resource
from hookah import queue
import urllib
import sys, os
from urllib import unquote
import cgi
import StringIO
import mimetools
import mimetypes
# TODO: Make these configurable
RETRIES = 3
DELAY_MUL... |
# Generated by Django 3.2.7 on 2021-12-02 21:01
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('Author', '0001_initial'),
('Posts', '0001_initial'),
]
operations = [
migration... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
# Given a list of pts text files, build a complete dataset from it.
import glob
import os
import PIL.Image
import cv2
import numpy as np
from time import time
from argparse import ArgumentParser
from scipy.spatial import cKDTree
import tensorflow as tf
import SaddlePoints
import errno
def mkdir_p(path):
try:
os.... |
# Question 1
# This function converts miles to kilometers (km).
# Complete the function to return the result of the conversion
# Call the function to convert the trip distance from miles to kilometers
# Fill in the blank to print the result of the conversion
# Calculate the round-trip in kilometers ... |
#!/usr/bin/env python
import tyrell.spec as Stuff
from tyrell.interpreter import PostOrderInterpreter
from tyrell.enumerator import SmtEnumerator, RelaxedRandomEnumerator
from tyrell.decider import Example, ExampleConstraintDecider, SimpleSpiceDecider, ExampleConstraintPruningDecider
from tyrell.synthesizer import Syn... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import scipy.stats as stats
import numpy as np
import warnings
from ecdfgof import adtest, kstest
warnings.filterwarnings("ignore")
_long = [
("alpha", stats.alpha),
("anglit", stats.anglit),
("arcsine", stats.arcsine),
("argus", ... |
import pytest
from brownie import interface, RewardsManager, Contract
from utils.voting import create_vote
from utils.config import (lido_dao_voting_address,
lido_dao_agent_address,
balancer_deployed_manager,
lido_dao_token_manager_address,... |
import RPi.GPIO as GPIO
import time
HIN = 8
LIN = 10
freq = 500
class Motor:
def __init__(self, HIN=HIN, LIN=LIN, freq=freq):
GPIO.setmode(GPIO.BOARD)
GPIO.setup(HIN, GPIO.OUT)
GPIO.setup(LIN, GPIO.OUT)
self.high = GPIO.PWM(HIN, freq)
self.low = GPIO.PWM(LIN, freq... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Get hardware info from Bpod
"""
from pybpodapi.protocol import Bpod
from confapp import conf
my_bpod = Bpod()
my_bpod.close()
print("Target Bpod firmware version: ", conf.TARGET_BPOD_FIRMWARE_VERSION)
print("Firmware version (read from device): ", my_bpod.hardware.... |
import boto3
class DynamoDB(object):
def __init__(self, table_name):
self.resource = self._resource()
self.client = self._client()
self.table = self.resource.Table(table_name)
self.table_name = table_name
def _resource(self):
return boto3.resource('dynamodb')
def ... |
CCSettingsList = {'Simulink.SolverCC' : # Solver
{
'StartTime' : '0.0',
'StopTime' : 'inf',
'SolverMode' : 'SingleTasking',
'Solver' : 'FixedStepDiscrete'... |
# Телеграм-бот v.002 - бот создаёт меню, присылает собачку, и анекдот
import telebot # pyTelegramBotAPI 4.3.1
from telebot import types
import requests
import bs4
bot = telebot.TeleBot('5105972662:AAG24fr382U1_hosO4Zrb-tv_BTakAV1MPk') # Создаем экземпляр бота
# --------------------------------------------... |
import os, gzip, pickle, sys, datetime, struct
from glob import glob
import pandas as pd
import subprocess
import shutil
import numpy as np
from datetime import timedelta
from io import StringIO
from SWaN_accel import config
from SWaN_accel import utils
from SWaN_accel import feature_set
pd.options.mode.chained_assign... |
# -*- coding: utf-8 -*-
# @Author: Manuel Rodriguez <valle>
# @Date: 28-Aug-2017
# @Email: valle.mrv@gmail.com
# @Filename: models.py
# @Last modified by: valle
# @Last modified time: 15-Feb-2018
# @License: Apache license vesion 2.0
from __future__ import unicode_literals
from django.db.models import Q
from dj... |
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs42_detached_award_financial_assistance_1'
def test_column_headers(database):
expected_subset = {'row_number', 'place_of_performan... |
#!/opt/local/bin/pyuhon
#-*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import datetime
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.cm as cm
import sys
from mpl_toolkits.basemap import Basemap
import os
import calendar
#as... |
# Copyright 2020 Pulser Development Team
#
# 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... |
"""Views for the wordrelaygame app."""
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, render
from django.views.generic import View, DetailView, ListView
from .forms import WordForm
from .models import Story
class HomeView(DetailView... |
from CreateTimeGraphs import *
def create_diag(dc):
"""Time spent on TeamSpeak per user"""
globalTime = timedelta()
for u in dc.users:
# Time in seconds
u.time = timedelta()
for con in u.connections:
# Increase connected time
u.time += con.duration()
us = sorted(dc.users, key = lambda u: -u.time)
for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.