content stringlengths 5 1.05M |
|---|
#
# gtksel.py -- select version of Gtk to use
#
# Eric Jeschke (eric@naoj.org)
#
import ginga.toolkit
toolkit = ginga.toolkit.toolkit
have_gtk3 = False
have_gtk2 = False
# For now, Gtk 2 has preference
if toolkit in ('gtk2', 'choose'):
try:
import pygtk
pygtk.require('2.0')
have_gtk2 = ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-22 18:45
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('topics', '0007_auto_20170322_1054'),
('topics', '0006_auto_20170319_1524'),
]
opera... |
from .initialize import *
from scipy import stats
from ..utils.tools import drop_nan, splat_teff_to_spt,kernel_density
from tqdm import tqdm
import splat.simulate as spsim
import splat.evolve as spev
import splat.empirical as spe
import wisps
#import pymc3 as pm
from scipy.interpolate import griddata
#import theano.te... |
from sqlalchemy import Column, String, Integer
from .. import Base
from .base_model import BaseModel
class Item(Base, BaseModel):
__tablename__ = 'items'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String, nullable=False)
category = Column(String, nullable=True)
count... |
class Results(object):
"""
MIOSQP Results
"""
def __init__(self, x, upper_glob, run_time, status,
osqp_solve_time, osqp_iter_avg):
self.x = x
self.upper_glob = upper_glob
self.run_time = run_time
self.status = status
self.osqp_solve_time = osqp_so... |
import struct
from enum import IntEnum
from spherov2.commands import Commands
from spherov2.helper import to_bytes, to_int
from spherov2.listeners.system_info import Version, LastErrorInfo, ConfigBlock, ManufacturingDate, EventLogStatus
class SosMessages(IntEnum):
UNKNOWN = 0
SUBPROCESSOR_CRASHED = 1
class... |
# ------------------------------
# 154. Find Minimum in Rotated Sorted Array II
#
# Description:
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
#
# (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
#
# Find the minimum element.
#
# The array may contain duplic... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys
import os
import time
import math
class Message():
def __init__(self, user, message):
self.user = user
self.message = message
def __eq__(self, other):
return self.message == other.message
if os... |
import os
class Logger(object):
def __init__(self):
pass
@staticmethod
def LogDebug(msg):
Logger._Log('[D] ' + msg)
@staticmethod
def LogInformation(msg):
Logger._Log('[I] ' + msg)
@staticmethod
def LogWarning(msg):
Logger._Log('[W] ' + msg)
@stat... |
# 779. K-th Symbol in Grammar
"""
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row,
we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, ... |
from camp.timepix.run import TimePixRun
from camp.timepix.vmi import VmiImage
run_number = 178 # short run
timepix_run = TimePixRun(run_number)
# extract data
timepix_dict = timepix_run.get_events('centroided', ['x', 'y'], fragment='fragments,test_ion')
x, y = timepix_dict['x'], timepix_dict['y']
# show VMI image
v... |
from collections import defaultdict, Counter
from itertools import product, permutations
from glob import glob
import json
import os
from pathlib import Path
import pickle
import sqlite3
import string
import sys
import time
import matplotlib as mpl
from matplotlib import colors
from matplotlib import pyplot as plt
fro... |
# Generated by Django 2.2.7 on 2019-12-04 20:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('post', '0002_remove_comment_liked'),
]
operations = [
migrations.AddField(
model_name='post',
... |
import pandas as pd
# 1.1 Understanding the dataset
# ===================================================================================
# - Import the dataset into a pandas dataframe using the read_table method.
# Because this is a tab separated dataset we will be using '\t' as the value
# for the 'sep' argument whi... |
icon_player = 0
icon_player_horseman = 1
icon_gray_knight = 2
icon_vaegir_knight = 3
icon_flagbearer_a = 4
icon_flagbearer_b = 5
icon_peasant = 6
icon_khergit = 7
icon_khergit_horseman_b = 8
icon_axeman = 9
icon_woman = 10
icon_woman_b = 11
icon_town = 12
icon_town_steppe = 13
icon_village_a = 14
icon_vi... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
from os import (
listdir,
getcwd,
makedirs,
rename,
)
from os.path import (
isfile,
isdir,
join,
splitext,
basename,
)
from threading import Thread
from time import sleep
from urllib import error as request_error
from urllib.req... |
# (C) Copyright 2019-2022 Hewlett Packard Enterprise Development LP.
# Apache License 2.0
from pyaoscx.exceptions.generic_op_error import GenericOperationError
class ListDescriptor(list):
"""
Attribute descriptor class to keep track of a list that contains
pyaoscx_module objects simulating a Referenc... |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2018-2020 azai/Rgveda mods with yutiansut/QUANTAXIS
#
# 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... |
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from .. import exceptions
from ..models import Expense, Project, Timesheet
class ProjectTestCase(TestCase):
def test_str(self):
project = Project(name="test")
self.assertEqual(str(project), "test")
... |
# -*- coding: utf-8 -*-
"""
"""
from collections import OrderedDict
import os
import subprocess
import librosa
import numpy as np
import pandas as pd
import sklearn as sk
import sklearn.model_selection
import skimage as skim
import skimage.measure
import skimage.morphology
import skimage.restoration
from tqdm import... |
# coding: utf-8
from typing import List
from ...shared.data.shared_data import BaseData
from ...shared.data.from_import import FromImport
from .items.data_item import DataItem
class Data(BaseData):
flags: bool
allow_db: bool
quote: List[str]
typings: List[str]
requires_typing: bool
from_import... |
import datetime
import typing as T
from pqcli import random
def format_float(num: float) -> str:
ret = f"{num:.01f}"
if ret.endswith("0"):
ret = ret[:-2]
return ret
def format_timespan(timespan: datetime.timedelta) -> str:
num = timespan.total_seconds()
if num < 60.0:
return f"~... |
'''
A positive integer m is a sum of squares if it can be written as k + l where k > 0, l > 0 and both k and l are perfect squares.
Write a Python function sumofsquares(m) that takes an integer m returns True if m is a sum of squares and False otherwise. (If m is not positive, your function should return False.)
Here a... |
import bokeh.model
import bokeh.core.properties
import bokeh.util.callback_manager
class Collection(bokeh.model.Model):
objects = bokeh.core.properties.Dict(bokeh.core.properties.String, bokeh.core.properties.Instance(bokeh.model.Model))
def on_change(self, attr, *callbacks):
bokeh.util.callback_manage... |
"""
Aggregating results into DataPoints
Copyright 2015 BlazeMeter 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 ... |
from abstract_rl.src.data_structures.temporal_difference_data.trajectory_collection import TrajectoryCollection
class TrajectoryOperator:
"""
A simple evaluation operator interface.
"""
def transform(self, trajectory):
"""
Transform a trajectory with the current instance of the evalua... |
#!/usr/bin/env python3.5
import sys
import re
import os
import csv
def read_file(fname):
f = open(fname, 'r')
csv_reader = csv.reader(f, delimiter='~')
no_rows = 0
for row in csv_reader:
no_rows += 1
no_cols = len(row)
print("Row %d: columns = %d" % (no_rows, no_cols))
f.close()
print(".......... |
import talker.base
import talker.server
from talker.mesh import PeerObserver, LOG, PeerClient
class TopoMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.register_command("/peers", TopoMixin.command_peers)
self.register_command("/peer-listen", TopoMixin.com... |
from math import hypot
cat_opo = int(input("Digite a medida do cateto oposto: "))
cat_adj = int(input("Digite a medida do cateto adjacente: "))
hipotenusa = hypot(cat_adj, cat_adj)
print(hipotenusa)
|
"""add_agent_external_url_to_streamsets
Revision ID: 9d3d42cad294
Revises: 507ccc9cb1a6
Create Date: 2020-11-13 13:05:40.922113
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9d3d42cad294'
down_revision = '507ccc9cb1a6'
branch_labels = None
depends_on = None
... |
from mendeleev.fetch import fetch_table
from mendeleev import element
ptable = fetch_table('elements')
def nombre_atomico(simbolo):
return element(simbolo).name
def estados_oxidacion(simbolo):
return element(simbolo).oxistates
def numero_atomico(simbolo):
'''
regresa el numero atomico.
Uso: num_at(string) ... |
"""
Non-negative 1-sparse recovery problem.
This algorithm assumes we have a non negative dynamic stream.
Given a stream of tuples, where each tuple contains a number and a sign (+/-), it check if the
stream is 1-sparse, meaning if the elements in the stream cancel eacheother out in such
a way that ther is only a uniq... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Created on Fri Mar 26 15:14:34 2021
# Copyright © Enrico Gandini <enricogandini93@gmail.com>
#
# Distributed under terms of the MIT License.
"""Utils necessary to store data generated by 'Molecular Similarity Survey'
web app into an SQL database.
"""
from sqlalchemy ... |
s1 = ' \n'
print(s1.isspace()) # -- SP1
s2 = ' b '
print(s2.isspace()) # -- SP2
s3 = ' '
print(s3.isspace()) # -- SP3
s4 = ' \t'
print(s4.isspace()) # -- SP4
s5 = '10+3 = 13 '
print(s5.isspace()) # -- SP5
s6 = ' \f'
print(s6.isspace()) # -- SP6
|
import numpy as np
import xarray as xr
from itertools import combinations
import dask.array as dsa
from ..core import calc_cape
from ..core import calc_srh
from .fixtures import empty_dask_array, dataset_soundings
import pytest
@pytest.fixture(scope='module')
def p_t_td_1d(nlevs=20):
p = np.random.rand(nlevs)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-06 15:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fileupload', '0002_auto_20170726_2027'),
]
operations = [
migrations.AddFie... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from pyfdm import fdmexec
JSBSIM_ROOT = os.path.abspath('./data/jsbsim_data') + os.sep
print('JSBSIM_PATH : ' + JSBSIM_ROOT)
#Load
fdm = fdmexec.FGFDMExec(root_dir=JSBSIM_ROOT)
fdm.load_model("f16")
fdm.print_property_catalog()
|
import numpy as np
import math
import matplotlib.pyplot as plt
#### 11 July 13: E-M Coin Toss Example as given in Stanford EM tutorial* ####
# * http://algorithmicalley.com/archive/2013/03/29/the-expectation-maximization-algorithm.aspx
def get_mn_log_likelihood(obs,probs):
""" Return the (log)likelihood ... |
import pysam
import csv
import sys
import collections
class Variant(object):
def __init__(self, original, new, refdict):
self.original = original
self.new = new
self.chrom = self.original['CHROM']
self.position = int(self.original['POS'])
self.coordinates = (self.chrom, se... |
# coding=utf-8
from requests import Response
from monitorrent.plugins.status import Status
from monitorrent.plugins.trackers import TrackerSettings
from monitorrent.plugins.trackers.rutor import RutorOrgPlugin, RutorOrgTopic
from tests import use_vcr, DbTestCase
class RutorTrackerPluginTest(DbTestCase):
def setUp... |
#! /usr/bin/env python
"""
This script allows for the search of Sentinel-1 data on scihub.
Based on some search parameters the script will create a query on
www.scihub.copernicus.eu and return the results either as shapefile,
sqlite, or PostGreSQL database.
"""
# import modules
import getpass
import os
import logging... |
from cowsay_app.models import message
from django.shortcuts import render
from cowsay_app.models import message
from cowsay_app.form import addmessageForm
import subprocess
# Create your views here.
def index_view(request):
if request.method == 'POST':
form = addmessageForm(request.POST)
if form.is... |
from glob import glob
from pbr import util
from setuptools import setup
cfg = util.cfg_to_args()
cfg.update({
'data_files': [
('docs', glob('docs/*.rst'))
],
# 'pbr': True,
})
setup(
**cfg
)
|
#!/usr/bin/env python3
import os
import subprocess
from benchmark_main import maybe_via_docker
PWD = os.getcwd()
TESTDATA_ROOT = os.path.join(PWD, "test_data")
LONG_SBP = os.path.join(TESTDATA_ROOT, "benchmark.sbp")
CMD = ['./rust/bin/sbp2json']
subprocess.run(
maybe_via_docker(PWD, "haskell-sbp2json", CMD),
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
"""
LICENSE MIT
2020
Guillaume Rozier
Website : http://www.covidtracker.fr
Mail : guillaume.rozier@telecomnancy.net
README:
This file contains scripts that download data from data.gouv.fr and then process it to build many graphes.
I'm currently cleaning the code, plea... |
from half_tones.check_range import *
def FloydSteinberg(img, error: int, x, y, z):
if checkRange(x + 1, y, img):
img[x+1][y][z] = img[x+1][y][z] + (7/16) * error
if checkRange(x, y + 1, img):
img[x][y+1][z] = img[x][y+1][z] + (5/16) * error
if checkRange(x + 1, y + 1, img):
img[x+1]... |
from jackutil.containerutil import containerChecksum,featuresFromContainer,projectContainer
from jackutil.configuration import configuration
from jackutil.microfunc import shortnames,rename_columns
from tqdm.auto import tqdm
from backtest import tradesim_store
from backtest.tradesim_util import build_simulator,account_... |
import csv
import datetime
from typing import List
from typing import Any
from typing import Dict
import json
import os
import urllib
import urllib.request
import matplotlib
import matplotlib.pyplot as plt
from InstagramAPI import InstagramAPI
from .instagram.instagram_key import InstagramKey
from .api_interface impo... |
#! /usr/bin/env python3
a = 1
if a == 1:
pass
else:
print("Hello")
|
"""
Module: 'inisetup' on esp8266 v1.9.3
"""
# MCU: (sysname='esp8266', nodename='esp8266', release='2.0.0(5a875ba)', version='v1.9.3-8-g63826ac5c on 2017-11-01', machine='ESP module with ESP8266')
# Stubber: 1.1.2 - updated
from typing import Any
bdev = None
def check_bootsec():
pass
def fs_corrupted():
p... |
#!/usr/bin/env python
import os
import sys
for i in xrange(1,len(sys.argv)):
tmp1 = sys.argv[i].split('s')
tmp2 = tmp1[1].split('.')
out = tmp2[0] + '.dat'
print sys.argv[i],out
command = 'mv '+sys.argv[i]+' '+out
os.system(command)
|
from titan.react_view_pkg import accountmenu
from . import accountmenu, formsmodule, formview, router, router_and_module, view
modules = [
accountmenu,
formsmodule,
formview,
router,
router_and_module,
view,
]
|
import unittest
from unittest.mock import patch, MagicMock
from botocore.exceptions import UnknownServiceError
from mypy_boto3_builder.parsers.shape_parser import ShapeParser
# pylint: disable=protected-access
class ShapeParserTestCase(unittest.TestCase):
def test_init(self) -> None:
session_mock = Magi... |
# coding: utf-8
from __future__ import division, print_function
import os, sys
import tensorflow as tf
import time
import cv2
import numpy as np
from utils import plot_one_box
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
color_table = [[0, 255, 0], [255, 0, 0], [0, 0, 255]]
classes = ['face', 'mask', 'glasses']
def ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayPcreditHuabeiSceneprodBenefitSendResponse(AlipayResponse):
def __init__(self):
super(AlipayPcreditHuabeiSceneprodBenefitSendResponse, self).__init__()
self._ret... |
"""Test cases for the aioswitcher.schedules module."""
# fmt: off
from asyncio import AbstractEventLoop, wait
from binascii import unhexlify
from pytest import fail, mark, raises
from aioswitcher.consts import (HANDLED_EXCEPTIONS,
SCHEDULE_DUE_ANOTHER_DAY_FORMAT,
... |
#!/usr/bin/env python3
import sys
sys.path.insert( 0, '..' )
# this will later be a session multiplexer object in a module abstraction library
from Engines.POF_com import Session as POFSession
def Main():
config = POFSession.Config("config.ini")
testSession = POFSession(config)
testSession.login()
... |
import os
import sys
import shutil
import multiprocessing
from robosat_pink.tools import cover
from robosat_pink.geoc import config as CONFIG, params, utils
multiprocessing.set_start_method('spawn', True)
def main(dsPath,geojson,out):
params_cover = params.Cover(
dir=dsPath,
bbox=None,
... |
from setuptools import setup, find_packages
setup(
name="workflowy.automation",
packages=find_packages(),
author="Luke Merrett",
description="Scripts for automating Workflowy tasks using Selenium",
license="MIT",
url="https://github.com/lukemerrett/Workflowy-Automation",
install_requires=['... |
#!/usr/bin/python
"""
Overview: http://fabric.readthedocs.org/en/1.0.0/tutorial.html
Execution: http://fabric.readthedocs.org/en/1.0.0/usage/execution.html
Author(s): Prateek Gupta (prateek@bloomreach.com)
"""
import os
import os.path
import tempfile
import yaml
import sys
import time
import traceback
from fabric.ap... |
# -*- coding: utf-8 -*-
""" 数据库相关函数 """
import pickle
import sqlite3
from gensim.models import KeyedVectors
from .log import get_logger
class Word2VecDb:
def __init__(self, db_path):
print("Use: `{}`".format(db_path))
self.db = sqlite3.connect(db_path)
self.cur = self.db.cursor()
d... |
def initialise_rankings(input_text):
"""
Initialises the rankings with each player and a score of 0
:param input_text: A multi-line string containing player names
:return: A multi-line string containing all rankings
"""
player_list = input_text.split('\n')
# delete last empty line
del pl... |
# https://app.codesignal.com/arcade/intro/level-6/6cmcmszJQr6GQzRwW
def evenDigitsOnly(n):
# Return if all digits on a number are even. For this convert the
# number into a string so its individual digits can be itere
return all([int(digit) % 2 == 0 for digit in str(n)])
|
from codecs import decode
from os import link
from pathlib import Path
from subprocess import Popen, PIPE, STDOUT, call
def __base_cond(path: Path):
"""
Base condition for all link operations.
:param path: the base file/dir path
:return: True if the base file/dir name passed the base condition check
... |
#!/usr/bin/env python3
"""
Advent of Code 2015: Day #
"""
import os
import hashlib
SECRET_KEY = 'iwrupvqb'
def make_byte_string(n):
return "{}{}".format(SECRET_KEY, n).encode()
def first_half():
"""
first half solver:
find MD5 hashes which, in hexadecimal, start with at least five zeroes.
iwrupvq... |
#desafio31. maneira 1. desenvolva um progama que pergunte a distancia de uma viagem em km.
# calcule o preço da passagem cobrando R$0.50 por km para viagens de até 200 km e R$0.45 para viagens mais longas.
entrada = float(input('Qual é a distancia da sua viagem? '))
if entrada >= 1 and entrada <= 200 :
preco = entr... |
#!/usr/bin/env python3
import argparse
import sys
import contextlib
import importlib
def run(code, files=None, filter_=None, begin=None, end=None, imports=None):
if files is None:
files = [sys.stdin]
if imports is not None:
for imp in imports:
locals()[imp] = importlib.import_module(imp)
if begin is not None... |
#!/usr/bin/python
"""
recall.py: version 0.1.0
History:
2017/06/19: Initial version converted to a class
"""
# import some useful function
import numpy as np
import random
# Define a class that will handle remembering features and
# steering angles to be learn by the model.
class Recall:
def __init__(self, maxm... |
import re
import os
import glob
import json
import hashlib
import operator
import itertools
import subprocess
from collections import defaultdict
import tabulate
import pydot
import pysolr
import markdown
from bs4 import BeautifulSoup
from flask import Flask, send_file, render_template, abort, url_for, request, sen... |
import sys
import os
import subprocess
import matplotlib
import unittest
matplotlib.use('Agg')
script_dir = os.path.sep.join(
os.path.abspath(__file__).split(os.path.sep)[:-2] + ['examples']
)
def test_scripts(script_dir=script_dir):
passing = []
for dirname, _, filenames in os.walk(script_dir):
... |
import numpy as np
from ..local_interpolation import ThirdOrderHermitePolynomialInterpolation
from .runge_kutta import AbstractESDIRK, ButcherTableau
# This γ notation is from the original paper. All the coefficients are described in
# terms of it.
γ = 0.43586652150
a21 = γ
a31 = (-4 * γ**2 + 6 * γ - 1) / (4 * γ)
a3... |
import numpy as np
def si_sdr(reference, estimation):
"""
Scale-Invariant Signal-to-Distortion Ratio (SI-SDR)
Args:
reference: numpy.ndarray, [..., T]
estimation: numpy.ndarray, [..., T]
Returns:
SI-SDR
[1] SDR– Half- Baked or Well Done?
http://www.merl.com/publicati... |
import argparse
import logging
import sys
from block_server_subscriber.subscriber import Subscriber
from block_server_subscriber.databaseImp import DatabaseImp
from block_server_subscriber.event_handling import EventHandler
LOGGER = logging.getLogger(__name__)
def parse_args(args):
parser = argparse.ArgumentPar... |
from bbdata.base import *
from bbdata.uid import *
CONNECTIONSTATE_TYPE = [ CONTEXT_UID_SENSORDATAFACTORY, 64, 1, 0 ]
class ConnectionState(BBCompound):
def __init__(self, name='connectionstate'):
super(BBCompound, self).__init__(name)
self.name = ShortString('name')
self.state = Int('state')
self.message =... |
import mimetypes
import os
import time
import warnings
from typing import (
overload,
TYPE_CHECKING,
Optional,
Union,
Iterator,
Generator,
Iterable,
Dict,
)
from urllib.parse import urlparse
if TYPE_CHECKING:
import numpy as np
from docarray import DocumentArray, Document
clas... |
"""Test the popular tags API."""
from typing import List
from rest_framework.test import APITestCase
from blog.factories import PostFactory
from tests.decorators import authenticated
_TAG_FIELDS = {"id", "name", "post_count"}
@authenticated
class PopularTagTest(APITestCase):
"""Test the popular tags endpoint.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import copy
import os
import time
from contextlib import contextmanager
import numpy as np
import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from tensorflow.python.compiler.tensorrt.trt_convert import \
DEFAUL... |
import os
from os import path, system
import convert
def main():
folder = input(
'Enter the directory path containing SUMMARY.md or other *.md files:\n')
try:
c = convert.MdToPdf(folder)
p = path.abspath(c.output)
print(60 * '-')
print('Successfully converted!')
... |
"""import libraries"""
import os
from ibm_watson import LanguageTranslatorV3 #from IBM
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator#authenticator
from dotenv import load_dotenv
load_dotenv()
apikey = os.environ['apikey']
url = os.environ['url']
authenticator = IAMAuthenticator('rThbq2SZ8s2Re6QBulyKf... |
# -*- coding: utf-8; -*-
#
# @file customglyph.py
# @brief Compatibility with others glyphs enums.
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2017-10-16
# @copyright Copyright (c) 2015 INRA
# @license MIT (see LICENSE file)
# @details
class CustomGlyph(object):
def __init__(self, prefix, name, opts=None):... |
from bluesky.magics import BlueskyMagics
from .startup import sd
from .detectors import *
from .endstation import *
from .accelerator import *
from .optics import *
from .tardis import *
#
# Setup of sup. data for plans
#
sd.monitors = []
sd.flyers = []
sd.baseline = [theta, delta, gamma, muR,
sx, say,... |
'''
A python script to compute bandgap in zinc oxide
Requires 1 argument in command line: doscar file.
Example, python compute_bandgap doscar 0 10
Created by: Shiva Bhusal, Aneer Lamichhane.
'''
import sys
'''
Function to convert numbers in E+ and E- exponential format to
normal floating point numbers.
'''
def ... |
from datetime import date
from django.db import models
from groups.models import Student
from subjects.models import Lesson, Task
class Attendance(models.Model):
visit = models.BooleanField(default=False)
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
student = models.ForeignKey(Student, o... |
from . import UserTestCase, HTTPTestMixin
class LoginTest(UserTestCase, HTTPTestMixin):
def test_get_login(self):
response = self.anon_user.get('login')
data = self.assert200(response)
def test_login_valid(self):
response = self.anon_user.post('/login', data={
'password':... |
from TradingGym.OrderBook import OrderBook
class Strategy:
"""
Implements base strategy which holds constant orders
"""
def __init__(self):
self.sleep = 100 # ms
def action(self, position, history, old_book, market_book):
"""Override this method in subclasses"""
new_book = O... |
import sys
import numpy as np
#import matplotlib.pyplot as plt
#NOTES FROM ROSS - 9/9/15
#NOTE: W should be 42x7
#NOTE: Bias should be 1x7
#for linear regression -
#loss = 0.5*sum((scores-targets)^2)
#scores = Wx + b
#dL/dW = dL/dscores * dscores/dW
#dL/dscores = (score - y)
#dscores/dW = X
#so
#dL/dW = (score - y) ... |
#
# 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 us... |
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures._base import TimeoutError
import datetime
import shutil
import time
import pytest
import requests
from .test_utils import *
from glide import *
def test_placeholder_node(rootdir):
nodes = PlaceholderNode("extract") | CSVLoad("load")
g... |
from boa3.builtin import public
@public
def main(value: str, some_bytes: bytes) -> bool:
return value not in some_bytes
|
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, List, Optional
from botorch.models.gp_regression import FixedNoiseGP
from botorch.models.ke... |
import unittest
from poker.card import Card
from poker.hand import Hand
from poker.validators import PairValidator
class HandTest(unittest.TestCase):
def test_starts_out_with_no_cards(self):
hand = Hand()
self.assertEqual(hand.cards, [])
def test_shows_all_its_cards_in_technical_representation... |
from django.contrib import admin
from . import models
from apps.common.utils import register
class UserGroupAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'type', 'app')
admin.site.register(models.UserGroup, UserGroupAdmin)
register('user_group')
|
from datetime import timedelta
from beanie import DeleteRules
from fastapi import APIRouter, Depends, Response
from fastapi.logger import logger
from awesome_sso.exceptions import BadRequest, HTTPException, InternalServerError
from awesome_sso.service.depends import get_sso_user_id, sso_registration, sso_user
from aw... |
import asyncio
import logging
import sys
import pickle
from typing import Dict, Tuple
SEPARATOR = b'salih'
class MessageObject:
def __init__(self, function_name: str, message_id: int, *args, result=None, **kwargs):
self._function_name = function_name
self._message_id = message_id
self._... |
"""Overview of lists."""
from functions import demo, placeholders, getinput, Status, Demo
index = placeholders('index')
item = placeholders('item')
lst = placeholders('filled_list')
slice2 = placeholders('slice2')
slice3 = placeholders('slice3')
# A list is, well, a list of things. They are similar to
# arrays in ... |
# Networked Tecnology
# * ______________ networking ______________
# * | application | <==> | application |
# * -------------- --------------
# the <========> is called 'socket' (TCP connections)
# internet can be a socket
# A 'port' is an application-specific soft... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import sys
def get_xi_2d(quadrilateral,p):
[p0, p1, p2, p3] = quadrilateral
xp1 = p[0]
xp2 = p[1]
xp3 = p[2]
x11 = p0[0]
x12 = p0[1]
x13 = p0[2]
x21 = p1[0]
x22 = p1[1]
x23 = p1[2]
x31 = p2[0]
x32 = p2[1]
x33 = p2[2]
x41 = p3... |
class OpCode(object):
def __init__(self, arg):
self.arg = int(arg)
def execute(self):
pass
@staticmethod
def parseline(line, lineno):
code, arg = line.split()
try:
return OpCode.make(code, arg)
except ValueError:
raise(ValueError(f"line {... |
from . import api, commons
def check_params(line_id: str, station_id: str, direction_sens: str):
response = api.get_missions_next(line_id, station_id, direction_sens)
# invalid station
if response.ambiguityMessage is not None:
raise commons.RatpException(
"invalid line code and/or sta... |
# Generated by make-pins.py, do NOT edit!
PINS_AF = (
('LED1', (1, 'LPI2C1_SCL'), (3, 'GPT3_COMPARE1'), (5, 'GPIO3_PIN7'), (10, 'GPIO9_PIN7'), (11, 'FLEXPWM1_PWMX2'), ),
('LED2', (1, 'LPI2C1_SDA'), (3, 'GPT3_COMPARE2'), (5, 'GPIO3_PIN8'), (10, 'GPIO9_PIN8'), (11, 'FLEXPWM1_PWMX3'), ),
('LED3', (3, 'GPT3_COMPARE3'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.