content stringlengths 5 1.05M |
|---|
# %%
"""
Tutorial 8: Fitting
===================
In this example, we'll fit the `Imaging` data we simulated in the previous exercise. we'll do this using model images
generated via a `Tracer`, and by comparing to the simulated image we'll get diagnostics about the quality of the fit.
"""
# %%
#%matplotlib i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) University of St Andrews 2022
# (c) University of Strathclyde 2022
# (c) James Hutton Institute 2022
#
# Author:
# Emma E. M. Hobbs
#
# Contact
# eemh1@st-andrews.ac.uk
#
# Emma E. M. Hobbs,
# Biomolecular Sciences Building,
# University of St Andrews,
# North Haugh ... |
"""定义blogs的URL模式"""
from django.conf.urls import url
from . import views
urlpatterns = [
#主页
url(r'^$',views.index,name = 'index'),
#显示所有的主题
url(r'^titles/$',views.titles,name = 'titles'),
#显示特定主题的博客
url(r'^titles/(?P<title_id>\d+)/$',views.title,name = 'title'),
#用于添加新主题的网页
url(r'^new_title/$',views.new_title,name = ... |
from enum import Enum
class DriverTypes(Enum):
chrome = "CHROME",
firefox = "FIREFOX",
ie = "IE"
|
from django import forms
from ecomApp.models import Checkout,MyRating
class RatingForm(forms.ModelForm):
class Meta:
model = MyRating
fields=('rating',)
class OrderForm(forms.ModelForm):
class Meta:
model = Checkout
fields=('fullname','email','NameOnCard','Address','creditcar... |
import json
with open('movies.json', 'r', encoding='utf-8') as fin:
data = json.load(fin)
hits = data.get('hits')
for idx, movie in enumerate(hits, 1):
if 'comedy' in movie.get('genres'):
print("{}. {}".format(idx, movie.get('title', 'MISSING')))
data['hits'][0]['title'] = 'The Rundown 2, the revenge... |
import tensorflow as tf
# Use eager execution to embrace the upcoming tensorflow 2.0.
tf.enable_eager_execution()
x = tf.constant(4.5)
m = tf.multiply(x, x)
print("hello world {}".format(m))
|
from discord.ext import commands
class Info(commands.CommandError):
def __init__(self, message, **kwargs):
super().__init__(message)
self.kwargs = kwargs
class Warning(commands.CommandError):
def __init__(self, message, **kwargs):
super().__init__(message)
self.kwargs = kwarg... |
"""
The operators specified in this module act like their matrix equivalent,
and attempt to match tbe basic building blocks in NumPy and other numerical
packages.
"""
import numpy as np
from functools import partial
from pyop import LinearOperator, matmat
from scipy.misc import doccer
docdict = {
'shape' :
"""... |
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from jarvis import consumers
websocket_urlPattern=[
path('ws/jarvis/',consumers.botConsumer.as_asgi()),
]
application=ProtocolTypeRouter({
# 'http':
'websocket':AuthMiddlewa... |
from enum import Enum
from torch import nn as nn
from daain.model.normalising_flow.coupling_blocks.attention_blocks import ApplyModuleOnSplit
from daain.model.normalising_flow.coupling_blocks.attention_blocks.fixed_distance_attention import (
FixedDistanceAttention,
)
from daain.model.normalising_flow.coupling_bl... |
__author__ = 'mdavid'
from flask import request, Response
from redis import Redis
from addressimo.blockchain import cache_up_to_date
from addressimo.config import config
from addressimo.crypto import generate_bip32_address_from_extended_pubkey, generate_payment_request, get_unused_presigned_payment_request, derive_br... |
import mock
from piecrust.app import PieCrust
from piecrust.appconfig import PieCrustConfiguration
def get_mock_app(config=None):
app = mock.MagicMock(spec=PieCrust)
app.config = PieCrustConfiguration(values={})
return app
def get_simple_content_item(app, slug):
src = app.getSource('pages')
asse... |
from numpy import *
import random
import numpy
##import pylab
from math import *
def dist(x,y):
return sqrt(numpy.dot(x-y,x-y))
class Histogram:
min=0.0
max=5.0
delta=0.05
numSamples=0
bins=numpy.array([0])
def add(self,val):
if self.min<val and val<... |
import json
import copy
import string
import itertools
import numpy as np
from random import choice
from decimal import Decimal
from typing import Any, Dict, List, Tuple, Callable
import collections
from collections import defaultdict
from allennlp.common.file_utils import cached_path
from allennlp.tools.s... |
from datetime import date, datetime, time
from unittest2 import TestCase
from urllib import unquote
from scheme.formats import *
class TestStructuredText(TestCase):
def assert_correct(self, pairs):
for unserialized, serialized in pairs:
self.assertEqual(StructuredText.serialize(unserialized), ... |
#39 Sound Levels
#Asking the decibel level of Noise
x = float(input("Enter the decibel level of noise = "))
if x == 130:
print("Jackhammer.")
elif x == 106:
print("Gas lawnmower.")
elif x == 70:
print("Alarm clock.")
elif x <= 40 :
print("Quiet room.")
elif 130 > x > 106:
print("Jackham... |
# Copyright © 2021 TerminalWarlord
# Encoding = 'utf-8'
# Licensed under MIT License
# https://github.com/TerminalWarlord/
import requests
from bs4 import BeautifulSoup as bs
def latestepisodes():
r = requests.get('https://ajax.gogo-load.com/ajax/page-recent-release.html?page=1&type=1')
soup = b... |
""" Sahana Eden Module Automated Tests - HRM006 Add Staff To Office
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
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 S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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... |
### sgfparser.py parses .sgf files. Each parse takes a file and creates a list
### of ParsedNodes. The list of nodes may not adhere to normal game moves such
### as alternating colors, or starting with B in an even game and W with
### handicaps. The first node is the root node and should be game properties
### w... |
#!/usr/bin/env python
"""
@file plot_caffe_ensemble_logloss.py
@brief plot caffe ensemble logloss (single vs ensemble)
@author ChenglongChen
"""
import sys
import numpy as np
from matplotlib import pyplot as plt
def main():
# collect argvs
log_file_single = sys.argv[1]
log_file_ensemble = sys.argv[2]
... |
from typing import List, Union
from yattag import Doc
from ..exceptions import WQXException
from .BibliographicReference import BibliographicReference
from .SimpleContent import (
CellFormName,
CellShapeName,
FunctionalFeedingGroupName,
HabitName,
TaxonomicPollutionTolerance,
Taxon... |
"""
General-purpose components useful in all viewdom_wired apps.
"""
from dataclasses import dataclass
from viewdom import VDOM
@dataclass
class Super:
parent_children: VDOM = ()
def __call__(self) -> VDOM:
return self.parent_children
|
import sys
import os
import shutil
import setuptools
if sys.argv[-1] == "publish":
# if os.system("pip freeze | grep wheel"):
# print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
# sys.exit()
if os.system("pip freeze | grep twine"):
print("twine not installed.\nUse `pip i... |
# Copyright 2019 Elasticsearch BV
#
# 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 applicabl... |
#
# create_tensors.py
#
# Author(s):
# Matteo Spallanzani <spmatteo@iis.ee.ethz.ch>
#
# Copyright (c) 2020-2021 ETH Zurich.
#
# 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... |
import unittest
import pqkmeans
import numpy
import pipe
class TestPQEncoder(unittest.TestCase):
def data_source(self, n: int):
for i in range(n):
for _ in range(3):
yield [i * 100] * 6
def setUp(self):
self.encoder = pqkmeans.encoder.PQEncoder(num_subdim=2)
d... |
from .connection import MysqlConnection
from .queryRunner import MysqlQueryRunner
from .queryBuilder import MysqlQueryBuilder
from .tableBuilder import MysqlTableBuilder
|
import attr
import logging
from functools import reduce
from typing import List, Dict, Union, Tuple, Optional
import jstruct.utils as utils
logger = logging.getLogger(__name__)
REQUIRED = True
struct = attr.s(auto_attribs=True)
class _JStruct:
"""A typing definition wrapper used to defined nested struct.
... |
def setup_parser(common_parser, subparsers):
parser = subparsers.add_parser("genotype", parents=[common_parser])
parser.add_argument(
"-i",
"--gram_dir",
help="Directory containing outputs from gramtools `build`",
dest="gram_dir",
type=str,
required=True,
)
... |
# -*- coding: utf-8 -*-
import datetime
import time
import os
import configparser
from PIL import Image
import telebot
PATH_TGCONFIG = 'tgsettings.ini'
#global tgconf
#global bot_result
#global tgbot
def newdir(tpath):
"""
Создание директории.
@param tpath: Имя директории.
"""
try:
os.mkd... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import numpy as np
import tamkin
from pyiron.atomistics.job.atomistic import Trajectory
from molmod.units import *
fro... |
import pathlib
import datetime
from loguru import logger
try:
import runrex.post.variable_builder as vb
except ImportError as ie:
logger.error('Need to install pandas: `pip install pandas`.')
raise ie
VARIABLES = {
'panc_with_competing_dx': ('+pancreatitis', '+competing_dx', '-competing_dx_NEGATIVE'),... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import corner
import numpy as np
import pandas as pd
import emcee
import sys
import mm_likelihood
from astropy.time import Time
import commentjson as json
import mm_param
import mm_make_geo_pos
from tqdm import tqdm
import functools
class ReadJson... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
START_DT = datetime(2018,5,23,0)
default_args = {
'owner': 'cdwanze',
'depends_on_past': False,
'start_date': START_DT,
'retries': 1... |
import os
import unittest
from test import support
from test.support import import_helper
# skip tests if _ctypes was not built
ctypes = import_helper.import_module('ctypes')
ctypes_symbols = dir(ctypes)
def need_symbol(name):
return unittest.skipUnless(name in ctypes_symbols,
'{!r... |
from zquantum.core.graph import (
generate_random_graph_erdos_renyi as _generate_random_graph_erdos_renyi,
generate_random_regular_graph as _generate_random_regular_graph,
generate_graph_from_specs as _generate_graph_from_specs,
save_graph,
)
import json
from typing import Union, Dict, Optional
def ge... |
from PIL import Image
from sys import argv
if len(argv) != 4:
exit("usage: python resize.py n infile outfile")
n = int(argv[1])
infile = argv[2]
outfile = argv[3]
inimage = Image.open(infile)
width, heigh = inimage.size
outimage = inimage.resize((width * n, height * n))
outimage.save(outfile)
# To resize small... |
#!/usr/bin/python
Import ("env")
import os
def main():
input = "otapass.txt"
if not os.path.exists(input) or not os.path.isfile(input):
print(f"Error: {input} does not exist.")
env.Exit(1)
password = ""
with open(input) as f:
password = f.readline()
password = password.s... |
import time
import sys
import json
import threading
import wieraCommon
from pprint import pprint
from LocalInstanceToWieraIface import *
from LocalInstanceToWieraIface.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.s... |
from telethon import events
import asyncio
from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern="ttf ?(.*)"))
async def get(event):
name = event.text[5:]
m = await event.get_reply_message()
with open(name, "w") as f:
f.write(m.message)
await event.delete()
await borg.send_file(ev... |
from .canvas import DefaultCanvas
from ...cell_fabric.generators import *
from ...cell_fabric.grid import *
import logging
logger = logging.getLogger(__name__)
class ResGenerator(DefaultCanvas):
def __init__(self, pdk, fin, finDummy):
super().__init__(pdk)
self.finsPerUnitCell = fin + 2*finDummy
... |
#!/usr/bin/env python
#
# Copyright (c) 2012, JT Olds <hello@jtolds.com>
#
# 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 us... |
#!/usr/bin/env python3
import os
import subprocess
import sys
def main():
result = subprocess.run(['pip', 'show', 'pip-tools'], stdout=subprocess.PIPE)
if not result.stdout.strip():
print('This script requires the pip-tools package be installed:\n'
' pip install pip-tools', fg='white... |
# -*- coding: utf-8 -*-
"""Classes for main Scryfall cache objects."""
import logging
import os
import shutil
import time
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import appdirs
from pony import orm
import requests
from requests_ratelimit_adapter import HTTPRat... |
import os
from flask import Flask, request, jsonify, abort
from sqlalchemy import exc
import json
from flask_cors import CORS
from .database.models import db_drop_and_create_all, setup_db, Drink
from .auth.auth import AuthError, requires_auth
app = Flask(__name__)
setup_db(app)
CORS(app)
'''
@TODO uncomment the foll... |
"""
MIT License
Copyright (c) 2021-present RPS
Copyright (c) 2015-2021 Rapptz
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, ... |
"""
Chatroom defines handlers for client behavior such as connecting and sending messages
"""
import random
import logging
from string import Template
from collections.abc import Iterable
from utils import log, log_message
from user import User
from command_handler import CommandHandler
from config_manager import Confi... |
import pykorm
class Score(pykorm.models.Nested):
exterior: int = pykorm.fields.DataField('exterior')
delicious: int = pykorm.fields.DataField('delicious', 10)
class ScoreMixin(object):
score: Score = pykorm.fields.DictNestedField(Score, path=['spec', 'score'])
@pykorm.k8s_custom_object('pykorm.infoman... |
from SPJRUD import SPJRUD
from SPJRUD.Select import Select
from SPJRUD.Project import Project
from SPJRUD.Join import Join
from SPJRUD.Rename import Rename
from SPJRUD.Union import Union
from SPJRUD.Difference import Difference
from Ope.Equal import Equal
from Representation.Constante import Constante
from Representati... |
import os
import time
import operator
import argparse
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn import metrics
from utils import timer, load_and_preprocess, load_trained_model
def fit_and_eval(X_train, y_train, X_val, y_val, module, pret... |
import requests
import re
import time
from datetime import datetime
import json
from tqdm import tqdm
import numpy as np
import seaborn as sns
from matplotlib import patches
import pandas as pd
import parser
import sys
import random
from collections import Counter
from bs4 import BeautifulSoup
from sklearn import prepr... |
import platform, os, json, discord
from time import sleep
from random import randint, choice
from threading import Thread
from colored import fg
from discord.ext import commands
from colorama import Fore
from discord.ext.commands import bot
from requests_futures.sessions import FuturesSession
s = Fore.RESET
f... |
#!/usr/bin/env python
# coding: utf8
"""Download metadata from the DBLP archive.
Usage
-----
```
$ python scripts/parse_dblp.py proceedings.json
```
"""
import argparse
import logging
import json
import os
import pandas as pd
import sys
import time
import tqdm
import zen.models
def parse_one(rec):
pass
def pa... |
#date and time
import datetime
current_date=datetime.date.today()
print(current_date)
print(current_date.month)
print(current_date.year)
print("Current date is: "+str(current_date.day))
|
import numpy as np
# # Problem domain definition
# # *******************************************************
# state = [0, 1, 2, 3, 4]
# action = [0, 1, 2], representing moving left, staying, moving right respectively
# Transition probability
T = np.array([ [[1/2,1/2,0,0,0], [1/2,1/2,0,0,0], [2/3,1/3,0,0,0]], [[1/3,... |
"""Disaster Tweet Classification, Helpers
This module provides helper functions, to be used for the naive Bayes algorithm of main.py. The
purposes of the helper functions relate to reading files, checking render, dividing original
training set into two sets, and tokenizing and normalizing the text data.
They are not ... |
try:
import urllib.request as urllib_request
import urllib.error as urllib_error
import io
except ImportError:
import urllib2 as urllib_request
import urllib2 as urllib_error
import json
from ssl import SSLError
import socket
import sys, select, time
from .api import TwitterCall, wrap_response, Twi... |
import math
def math_pow_test(x, y):
return math.pow(x, y)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
warnings.filterwarnings('ignore')
__tool_name__='STREAM'
print('''
_____ _______ _____ ______ __ __
/ ____|__ __| __ \| ____| /\ | \/ |
| (___ | | | |__) | |__ / \ | \ / |
\___ \ | | | _ /| __| / /\ \ | |\/|... |
from datetime import datetime
from getCryptocurrencyRate import CryptoCurrencyRate
product = "BTC_JPY"
# ["BTC_JPY", "XRP_JPY", "ETH_JPY", "XTZ_JPY", "XLM_JPY", "XEM_JPY", "BAT_JPY", "ETC_JPY", "LTC_JPY", "BCH_JPY", "MONA_JPY", "LSK_JPY"]
scale = "hour"
# ["hour","day","week","month","year"]
res = CryptoCurrencyRate... |
"""
Am examplar script showing inference on the newly collected images in U3DPW.
"""
import sys
sys.path.append("../")
import libs.model.model as libm
from libs.dataset.h36m.data_utils import unNormalizeData
import torch
import numpy as np
import imageio
import matplotlib.pyplot as plt
import time
num_joints = 16
... |
# Copyright (c) 2020 Jason Dsouza <jasmcaus@gmail.com>
# Protected under the MIT License (see LICENSE)
# Surpressing Tensorflow Warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 0 = all messages are logged (default behavior)
# 1 = INFO messages are not printed
# 2 = INFO and WARNING messages are not print... |
import mmapi;
def vectori_to_list(vi):
"""convert a SWIG vectori object to a Python list"""
sz = vi.size()
lst = []
for i in xrange(0,sz):
lst.append( vi[i] )
return lst
def vectorub_to_string(vub):
"""convert a SWIG vectorub object to a Python string"""
sz = vub.size()
lst = [... |
#!/usr/bin/env python
"用匿名管道从子进程向父进程发送数据,并将管道描述符封装进文件对象"
import os
import time
def child(pipe_out_int):
"子进程"
sleep_int = 0
while True:
# time.sleep(0.01) # 防止向管道输出端发送的数据流重叠
time.sleep(sleep_int) # 模拟实际工作,让父进程等待
msg_bytes = ('Spam {}\n'.format(sleep_int)).encode() # 管道是二进制字节
os.write(pipe_out_int, msg_... |
from syft.interfaces.keras import actual_keras
def load_data():
return actual_keras.keras.datasets.mnist.load_data() |
from webpie import WPApp, WPHandler, HTTPServer, HTTPSServer
class H(WPHandler):
def redirect1(self, request, relpath, to=None):
return "redirect", 301, {"Location":to}
def redirect2(self, request, relpath, to=None):
print("app: request.path_url:", request.path_url)
self.redirect(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from keras import layers
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.tf_utils import shape_type_conversion
@register_keras_serializable(package='... |
import math
def cut_evenly(weights, threshold):
min_weight = min(weights)
weights = [w / min_weight for w in weights]
intervals = [None] * len(weights)
base_cuts = 0
for i, weight in enumerate(weights):
if weight > 1:
a, b = weight * threshold, weight / threshold
in... |
"""
Migration script to add the post_job_action_association table.
"""
from sqlalchemy import *
from migrate import *
from migrate.changeset import *
from galaxy.model.custom_types import *
import datetime
now = datetime.datetime.utcnow
import logging
log = logging.getLogger( __name__ )
metadata = MetaData( migrate... |
from typing import List, Tuple
from mypy.plugin import Plugin
from mypy.nodes import MypyFile
class DepsPlugin(Plugin):
def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]:
if file.fullname == '__main__':
return [(10, 'err', -1)]
return []
def pl... |
# импотрирую для работы со знаками припинания.
import string
# тут лежат регулярные выражения похоже на sql
import re
# для приведения слов к первой форме
import pymorphy2
text = open('texst_lesson_3.txt', 'r', encoding='UTF-8') # Для винды обязательно писать кодировку иначе ошибка
text_1 = text.read()
'''проверка пр... |
# -*- coding: utf-8 -*-
"""
UNIVERSIDAD EL BOSQUE
PROYECTO INTEGRADO - TRANSFORMADAS / TRANSDUCTORES
PEDRO GUILLEM
LUISA ECHEVERRY
DIANA NUNEZ
Copyright:
Autor: PEDRO GUILLEM
Generado usando PyQT4 desde ui_plot.ui
"""
# Form implementation generated from reading ui file 'ui_plot.ui'
#
# Created: Sat Nov 5 22:10:24... |
#!/usr/bin/python3
import sys
# sum all the values associated with keys to get the score of each subreddit
word = None
count = 0
upvotes=0
downvotes=0
for line in sys.stdin:
username, value,ups,downs = line.strip().split()
if word is None: # runs first time the only in the loop
word = username
eli... |
import hikari
import tanjun
import os
import logging
from dotenv import load_dotenv
import lavasnek_rs
load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
LAVALINK_HOST = os.getenv("LAVALINK_HOST")
LAVALINK_PASSWORD = os.getenv("LAVALINK_PASSWORD")
LAVALINK_PORT = os.getenv("LAVALINK_PORT")
logging.basicConfig... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of SyncBoom and is MIT-licensed.
# Originally based on microblog, licensed under the MIT License.
from flask import render_template, current_app
from flask_babel import _
from app.email import send_email
def send_password_reset_email(user):
... |
import numpy as np
from .base import OdeSolver, DenseOutput
from .common import (validate_max_step, validate_tol, select_initial_step,
norm, warn_extraneous, validate_first_step)
from . import dop853_coefficients
# Multiply steps computed from asymptotic behaviour of errors by this.
SAFETY = 0.9
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('extranet', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='issue',
name='estim... |
# -*- coding: utf-8 -*-
#
# dbscan_cluster.py
#
# Copyright 2017 Sebastian Spreizer
# The MIT License
import numpy as np
from sklearn.cluster import DBSCAN
__all__ = [
'detect',
]
def detect(data, eps=1, min_samples=10, core_samples_mask=False):
X = np.vstack(data).T
db = DBSCAN(eps=eps, min_samples=mi... |
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers. See the top-level LICENSE file for dates and other
# details. No copyright assignment is required to contribute to VisIt.
"""
file: test_common.py
author: Cyrus Harrison (cyrush@llnl.gov)
created: 4/9/2010
description... |
from Crypto.Cipher import AES
class DecrypterProvider(object):
def __init__(self, network, m3u8, get_by_comparison = False):
self.__network = network
self.m3u8 = m3u8
self.key = None
self.uri = self.m3u8.data["keys"][1]["uri"]
if get_by_comparison:
self.get_key_... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from libtbx.program_template import ProgramTemplate
from mmtbx.secondary_structure import ss_validation
# =============================================================================
class Program(ProgramTemplate):
description = '''
phenix.... |
import requests
import os
import glob
from datetime import datetime, timedelta
def get_config(config_path):
"""
Funciton to get configuration file from online repository
"""
# Try to get config file or raise exception
try:
if config_path.startswith('http'):
r = requests.get(co... |
from securityheaders.checkers import Finding, FindingType, FindingSeverity
from .cspcheck import CSPCheck
class CSPCheckDeprecated(CSPCheck):
def __init__(self, csp):
self.csp = csp
def check(self):
csp = self.csp
if not csp or not csp.parsedstring:
return []
... |
from typing import Dict
import pytest
from django.apps import apps
from django.core import management
from django.test import RequestFactory
from radical_translations.agents.models import Organisation, Person
from radical_translations.agents.tests.factories import (
OrganisationFactory,
PersonFactory,
)
from ... |
# http://github.com/timestocome
# source code from
# https://github.com/bashardawood/L3G4200D-Python/blob/master/gyro.py
# data sheet
# https://www.parallax.com/sites/default/files/downloads/27911-Gyroscope-3-Axis-L3G4200D-Guide-v1.1.pdf
# i2c must be set up on Raspberry Pi first
# https://learn.adafruit.com/adafrui... |
# coding: utf-8
from __future__ import unicode_literals
import pandas as pd
from dframcy import utils
class DframCy(object):
"""
Dataframe integration with spaCy's linguistic annotations.
"""
def __init__(self, nlp_pipeline):
"""
:param nlp_pipeline: nlp pipeline to be used (i.e. la... |
from collections import namedtuple
from typing import List, Tuple, Optional
import numpy as np
from dijkstar import Graph
from src.kinematics.forward_kinematics import geometric_jacobian
from src.kinematics.joints import BaseJoint
from src.prechecks.trajectory_segment import JointTrajSegment
START_NODE = -1
STOP_NOD... |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype decorator code generator magic** (i.e., global constants simplifying
code generation but *not* themselves code).
This p... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# use Gauss's foumula
expected = len(nums) * (len(nums)+1) // 2
return expected - sum(nums)
|
import subprocess, time
import TM1637
import board
if __name__ == "__main__":
CLK = board.D6
DIO = board.D13
display = TM1637.TM1637(CLK, DIO)
display.hex(0xbeef)
time.sleep(5)
while True:
t = time.localtime()
display.numbers(t.tm_hour,t.tm_min)
time.sleep(60-(t.tm_sec%60))
|
import os
import h5py
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
#from models.nasnet.debug import read_output
######################################################################
## Load parameters from HDF5 to Dict
###################################################... |
"""
Script for serving.
"""
import torch
from bedrock_client.bedrock.model import BaseModel
from PIL import Image
from torchvision.models import resnet50
from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
class Model(BaseModel):
def __init__(self):
self.device = torch.devi... |
from django.shortcuts import render, redirect
from . import forms
from . import models
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from profiles.models import Status
import random
def randomGen():
# return a ... |
"""
Two possible solutions.
One alters the list you used in the function call. If you do not
want this behavior; for instance you want to keep your original list while
having a separate swapped version; you need to have the second one.
"""
def swap(alist,index1,index2):
if index1 + 1 > len(alist) or index2 +1 > len... |
from pypresence import Presence
import time
import config
import event_manager
import logger
from string_util import replace_text
from time import sleep
SETTINGS = config.get_config()
client_id = SETTINGS["discord"]['application_id']
connected = False
retries = 0
max_retries = 3
RPC = None
def initialize():
glo... |
# -*- coding: utf-8 -*-
import unittest
from .. import spec
class test_spec(unittest.TestCase):
def test_cmd_parser(self):
cmds = [
(
"zapimage sampy 0 1 10 sampz 2 3 11 100",
{"time": lambda x: x.to("ms").magnitude == 100},
),
(
... |
# Provides useful functions
import os
import sys
import argparse
import subprocess
import signal
# Default arguments
ex_parser = argparse.ArgumentParser()
ex_parser.add_argument("-V", "--version",action="store_true", help="Show version")
ex_parser.add_argument("-q", "--quiet", action="store_true", help="Disable outpu... |
import io
import pycurl
from time import gmtime, strftime
import stem.process
from stem.util import term
# reference: https://stem.torproject.org/tutorials/to_russia_with_love.html
SOCKS_PORT = 7000
# generated by 1.3.2_find_exitnodes.py
countries_with_exit_node = ['us', 'de', 'ch', 'ru', 'no', 'at', 'se', 'nl', 'bg'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.