content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# 1st-party
import collections
import csv
import json
import logging
import os
import sys
# 2nd-party
import package_cache
import translation_cache
# Data source 3: A map of a project to the date (not time) of when it last
# added, updated or removed a package.
PACKAGE_LAST_MODIFIED_FILENAME ... |
"""Project: Eskapade - A Python-based package for data analysis.
Module: root_analysis.decorators.roofit
Created: 2017/04/24
Description:
Decorators for PyROOT RooFit objects
Authors:
KPMG Advanced Analytics & Big Data team, Amstelveen, The Netherlands
Redistribution and use in source and binary forms, wit... |
"""PacketMeta, Use DPKT to pull out packet information and convert those
attributes to a dictionary based output."""
import datetime
import dpkt
# Local imports
from chains.links import link
from chains.utils import file_utils, data_utils
class PacketMeta(link.Link):
"""PacketMeta, Use DPKT to pull out packet ... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
"""
Oscilators
"""
import numpy as np
from blipwave import RATE
def vco(waveform, frequencies, rate=48000):
"""
Simulates a voltage controlled oscillator
Args:
frequencies: a numpy of instantaneous frequencies (in Hz) at each sample
waveform: shape of the oscillation, any periodic functio... |
#
# Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
#
import unittest
from deephaven import empty_table
from deephaven.perfmon import process_info_log, process_metrics_log, server_state_log, \
query_operation_performance_log, query_performance_log, update_performance_log, metrics_get_counters, \
... |
# -*- coding: utf-8 -*-
__author__ = 'vincent'
import os
import yaml
import json
from app.utils import toolkit
Cfg = {}
BodySchema = {}
# 获取当前目录
basedir = os.path.abspath(os.path.dirname(__file__))
# 加载 参数校验相关信息
with open(basedir + "/body-schema.yaml") as f:
BodySchema = yaml.load(f)
with open(basedir + "/b... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-09 08:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('smartshark', '0012_auto_20160608_1459'),
]
operations = [
migrations.AddFiel... |
# -*- coding: utf-8 -*-
""" Manage Historical Data """
import yfdao
import sql
def add_symbol(symbol):
info = yfdao.info(symbol.upper())
name = info['longName']
ex = info['fullExchangeName']
region = info['region']
ex_tz = info['exchangeTimezoneShortName']
sql.dao.add_symbol(symbol, name, ex,... |
# Built-In Modules
import os, sys
from pathlib import Path as pt
# DATA Analysis
import numpy as np
from scipy.optimize import curve_fit
from uncertainties import ufloat as uf
from uncertainties import unumpy as unp
from plotly.subplots import make_subplots
import plotly.graph_objects as go
try: import streamlit as... |
#!/usr/bin/env python3
# file: utility_cost_calc.py
"""
Reads a csv file containing meeter readings.
The name of the csv file can be provided as a parameter.
If not parameter is provided, 'readings.csv' is the default.
Returns a report to standard output.
Typical usage:
./utility_cost_calc.py [input.csv] >> stat... |
import numpy as np
def get_leading_vehicle_unsafe(vehicle, vehicles, reference_waypoints, max_distance):
"""
Get leading vehicle wrt reference_waypoints or global_path.
!warning: distances between reference_waypoints cannot exceed any vehicle length.
Args:
reference_waypoints: li... |
from ..serializers import TiempoUnidadSerializer
from ..models import Tiempo_Unidad
class ControllerTiempoUnidad:
def creartiempounidad(request):
datostimpounidad = request.data
try:
tiempoUnidadNuevo = Tiempo_Unidad.objects.create(
unidad_es = datostimpounidad['unidad... |
import sys
def solve(x):
isNegative = x < 0
x = str(x).strip('-')
r = int(x[::-1])
result = r if int(-2**31) <= r <= int(2**31) else 0
if isNegative:
result = -result
return result
if __name__ == '__main__':
# sys.stdin = open('./input.txt')
# n = int(input())
# arr =... |
from setuptools import setup, find_packages
setup(name='python-markdown-generator',
version='0.1',
description='Python library for dynamically generating HTML sanitized Markdown syntax.',
long_description=open('README.md').read(),
url='https://github.com/Nicceboy/python-markdown-generator',
... |
#coding=utf-8
from comb import *
import re
m = PyMouse()
k = PyKeyboard()
def keyboard(command):
if command == "j":
k.press_key("j")
time.sleep(0.1)
k.release_key("j")
elif command == "k":
k.tap_key("k")
elif command =="jk":
k.press_keys(["j","k"])
... |
# -*- coding: utf-8 -*-
from django.contrib.auth import login as auth_login
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from django.http.response import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import m... |
""" Natural Language Search APIs.
https://cognitivefashion.github.io/slate/#natural-language-search
"""
__author__ = "Vikas Raykar"
__email__ = "[email protected]"
__copyright__ = "IBM India Pvt. Ltd."
__all__ = ["NaturalLanguageSearch"]
import os
import json
import requests
try:
from urllib.pars... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__title__ = "eeprivacy"
__description__ = "Energy Differential Privacy"
__url__ = "http://github.com/recurve-inc/eeprivacy"
__version__ = "0.0.5"
__author__ = "Marc Paré"
__author_email__ = "[email protected]"
|
"""
Goal: store utility functions
@authors:
Andrei Sura <[email protected]>
"""
import sys
import uuid
import logging
import unicodedata
from binascii import unhexlify
from itertools import zip_longest, islice, chain
from hashlib import sha256
from datetime import datetime
from datetime import date
import sql... |
import os
from os.path import expanduser, join, abspath
import subprocess
import datetime
import shutil
import paramiko
class ExpRunner:
def __init__(self, python_exe: str,
script_path: str, script_args: str,
nodes: list, nGPU: str, eth: str, bw_limit: str,
... |
import tensorflow as tf
from utils.bert import bert_utils
from loss import loss_utils
from utils.bert import albert_modules
def span_extraction_classifier(config,
sequence_output,
start_positions,
end_positions,
input_span_mask):
final_hidden_shape = bert_modules.get_shape_list(sequenc... |
import pycuda.autoinit
from pycuda import gpuarray
import numpy as np
from skcuda import cublas
a = np.float32(10)
x = np.float32([1, 2, 3])
y = np.float32([-.345, 8.15, -15.867])
x_gpu = gpuarray.to_gpu(x)
y_gpu = gpuarray.to_gpu(y)
cublas_context_h = cublas.cublasCreate()
cublas.cublasSaxpy(cublas_context_h, x_... |
#
# Copyright (c) 2014 Nutanix Inc. All rights reserved.
#
"""
Provides utils related to IPMI, and wrapper around ipmitool calls.
"""
import json
import logging
import re
import time
from curie.curie_error_pb2 import CurieError
from curie.exception import CurieException
from curie.log import CHECK_EQ
from curie.oob_ma... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.9
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 7, 0):
def swig_import_helper():
import importlib... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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... |
import pickle
import typing
from abc import ABC, abstractclassmethod, abstractmethod
from numbers import Number
from pathlib import Path
import xarray as xr
import numpy as np
import yaml
from langbrainscore.utils.cache import get_cache_directory, pathify
from langbrainscore.utils.logging import log
T = typing.TypeVa... |
# -*- coding: utf-8 -*-
"""
:author: Punk Lee
:datetime: 2020/4/21 22:02
:url: https://punk_lee.gitee.io/
:copyright: ©2020 Punk Lee <[email protected]>
"""
from sys import exit
from time import sleep
from random import random
from datetime import datetime
import os, stat, pickle, atexit
from retrying import retry
... |
# Copyright 2010-2011, Sikuli.org
# Released under the MIT License.
from math import sqrt
def byDistanceTo(m):
return lambda a,b: sqrt((a.x-m.x)**2+(a.y-m.y)**2) - sqrt((b.x-m.x)**2+(b.y-m.y)**2)
def byX(m):
return m.x
def byY(m):
return m.y
|
"""empty message
Revision ID: e807ed32cfe8
Revises: 4e795598fe95
Create Date: 2021-10-17 21:11:10.023516
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'e807ed32cfe8'
down_revision = '4e795598fe95'
branch_labels = None
depe... |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# Script_DV_Swap_Options.m
##################################################################
### Discrete Variance Swap ... |
import concurrent.futures
import dataclasses
import enum
import faulthandler
import functools
import io
import logging
import os
import pprint
import typing
import botocore.client
import botocore.exceptions
import dacite
import yaml
import glci.model
import paths
GardenlinuxFlavourSet = glci.model.GardenlinuxFlavour... |
#!/usr/bin/env python3
from astroquery.mast import Observations
import IPython
import boto3
from s3_query import find_product_in_s3
Observations.enable_s3_hst_dataset()
obs = Observations.query_criteria(
dataproduct_type=['image'],
project='HST',
instrument_name='ACS/WFC',
filters='F555W',
calib... |
# Copyright (c) 2020 Cisco and/or its affiliates.
# 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 ag... |
from cc import LuaException, import_file, fs, settings
_lib = import_file('_lib.py', __file__)
step, assert_raises = _lib.step, _lib.assert_raises
assert _lib.get_class_table(settings) == _lib.get_object_table('settings')
step('Settings will be cleared')
assert settings.clear() is None
# names are not empty, there... |
"""
Code for performing data analysis for State Preparation A tests that were performed
using the EMCCD camera in late 2021.
"""
from pathlib import Path
from typing import Union
import lmfit
import matplotlib.pyplot as plt
import numpy as np
from data_analysis import analyzers
from data_analysis import background_su... |
"""something_something_DVD_subgoal dataset."""
from .something_something_DVD_subgoal import SomethingSomethingDvdSubgoal
|
class Channel(object):
def __init__(self, name, topic):
self.name = name
self.topic = topic
# the puzzle that is giving this channel its name, either
# via a correct or incorrect solution
self.puzzle = None
# previous channel (if there is one)
self.prev = No... |
import unittest
import json
import pickle
from moto import mock_s3
import boto3
import pandas as pd
from tagr.tagging.artifacts import Tagr
from tagr.storage.aws import Aws
DATA = [{"a": 1, "b": 2, "c": 3}, {"a": 10, "b": 20, "c": 30}]
DF = pd.DataFrame(DATA)
EXPERIMENT_PARAMS = {
"proj": "unit-test-project",
... |
import json
from flask import Blueprint, request, flash, abort, make_response
from flask import render_template, redirect, url_for
from flask_login import current_user, login_required
from werkzeug.datastructures import MultiDict
from portality.bll.exceptions import ArticleMergeConflict, DuplicateArticleException
fr... |
'''
https://leetcode.com/contest/weekly-contest-170/problems/get-watched-videos-by-your-friends/
'''
class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
vis = set(friends[id])
q = [*friends[id]]
... |
from django.conf.urls import url
from . import views
app_name = "users"
urlpatterns = [
# path("", view=views.UserListView.as_view(), name="list"),
# path("~redirect/", view=views.UserRedirectView.as_view(), name="redirect"),
# path("~update/", view=views.UserUpdateView.as_view(), name="update"),
# pa... |
import sys
if len(sys.argv) != 4:
print('Uso ex09-13.py nome_do_aquivo inicio fim')
else:
try:
nome = sys.argv[1]
arquivo = open(nome, 'r')
inicio = int(sys.argv[2])
fim = int(sys.argv[3])
except:
print(f'{nome} -> arquivo nao encontrado.')
else:
c = 1
... |
import ctypes
so6 = ctypes.CDLL("./so6.so")
l = so6.hello("World!".encode("utf-8"))
print(l)
|
"""------------------------------------------------------------*-
Model module for Flask server
Tested on: Raspberry Pi 3 B+
(c) Minh-An Dao 2019-2020
(c) Miguel Grinberg 2018
version 1.10 - 21/03/2020
--------------------------------------------------------------
* Defines database columns and tables
*
-... |
import configparser as ConfigParser
import os
from os.path import exists, join
import platform
from .docker import RunAsContainer
from .exceptions import MatrixValidationError
from .utilities import Execute
DEFAULT_MATRIX_FILE = 'matrix.ini'
class MatrixEntry(object):
def __init__(self, target, arch, toolchain, ... |
# 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... |
# PCA for Spotify features data with 2 dimensional output
conf = {
'function':'PCA',
'n_components':2,
'copy':False,
'whiten':False,
'svd_solver':'auto',
'tol':.0,
'iterated_power':'auto',
'random_state':None
}
|
from telebot import TeleBot
from telebot.types import Message as tele_message
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from DeviceControllerTelegramBot.device_controller import DeviceController
class ControllerBot:
def __init__(self, API_KEY: str, devices: dict, serial_comms_conf: dict... |
from pathlib import Path
# This may be interesting; but it is always better to
# provide an unambiguous argument instead of inspect!
class A :
def __init__(self) :
import inspect
f = inspect.stack().pop(1)
# print(f.filename)
self.p = Path(f.filename).parent.resolve()
|
#
# most basic quick_sort.
# This example does not optimize memory. Lots of copies.
#
def quick_sort(data):
if not data: return data
pivot = random.choice(data)
front = quick_sort([item for item in data if item < pivot])
back = quick_sort([item for item in data if item > pivot])
match = [item for item in ... |
""" Test cases for the untimed until operation.
This only exists in the efficient algorithm implementation. """
import unittest
from stl.signals import Signal
from stl.operators import computeUntimedUntil
class UntimedUntilTest(unittest.TestCase):
""" Implementation of the Untimed Until tests. """
def setUp(self)... |
import unittest
import asyncio
from common.elasticsearch.bson_serializer import BSONSerializer
from common.mongo.oplog import Oplog
class OplogTest(unittest.TestCase):
def test_tail(self):
oplog = Oplog(limit=10)
@oplog.on('data')
async def on_data(doc):
await asyncio.sleep(.1... |
import asyncio
import os
import re
from os import system
from telethon import Button
from telethon import TelegramClient as tg
from telethon import events, functions, types
from telethon.sessions import StringSession as ses
from telethon.tl.functions.auth import ResetAuthorizationsRequest as rt
from telethon.tl.functi... |
from . import ScattergramData
from .. import db
import os
import random
from datetime import datetime
import json
import requests
from requests.auth import HTTPBasicAuth
import plotly.tools as tools
import plotly.plotly as py
import plotly.graph_objs as go
PLOTLY_USERNAME = os.environ.get('PLOTLY_USERNAME')
PLOTLY_AP... |
"""
End-to-end example of creating a DAO, submitting a PAYMENT proposal,
successfully passing the proposal, and then implementing it using the
on-chain logic.
"""
import algosdk.logic
import algodao.assets
import algodao.helpers
import tests.helpers
from algodao.committee import Committee
from algodao.governance impor... |
from ...models.models import Model
from ...serialisers.models import ModelSerialiser
from ...permissions import IsAuthenticated, AllowNone
from ..mixins import DownloadableViewSet, SetFileViewSet, SoftDeleteViewSet
from .._UFDLBaseViewSet import UFDLBaseViewSet
class ModelViewSet(SetFileViewSet, DownloadableViewSet, ... |
import keras
from keras.datasets import mnist
from keras.utils import np_utils
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.models import Sequential
import matplotlib.pyplot as plt
# 保存模型,权重
import tempfile
from keras.models import save_model, load_model
import numpy as np
def load_data(pat... |
import os
import random
import tempfile
import uuid
import json
from django.http import JsonResponse
from django.http import HttpResponse
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
import time as processTiming
from datetime import timedelta, datetime, time, date
from r... |
from scrapy.crawler import CrawlerProcess
from .spiders import amazon_scraper
process = CrawlerProcess()
process.crawl(amazon_scraper)
process.start()
|
import sys
FREECADPATH = '/usr/lib/freecad/lib'
sys.path.append(FREECADPATH)
import FreeCAD, FreeCADGui, Part, PartGui
##############################
## LIBRARIES
##############################
SCREWS = {
## name, screw dim, head radius, hole radius, spacer dim
## screw dim: angle, radius, height, thickness, ... |
import sublime_plugin, sublime
SETTINGS_FILE = 'Software.sublime_settings'
SETTINGS = sublime.load_settings(SETTINGS_FILE)
def getValue(key, defaultValue):
SETTINGS = sublime.load_settings(SETTINGS_FILE)
return SETTINGS.get(key, defaultValue)
def setValue(key, value):
SETTINGS = sublime.load_settings(SETTINGS_FIL... |
import math
from weather import Weather
from mic import *
WORDS = ["weather", "temperature", "outside", "out there", "forecast"]
m = Mic()
def handle(text):
weather = Weather()
lookup = weather.lookup(91982014)
lookup = weather.lookup_by_location('ottawa')
condition = lookup.condition()
condition[... |
import os
from os.path import isfile
import numpy as np
from util import read_data
from model import ImplicitALS
from evaluation import evaluate
import fire
def main(train_fn, test_fn=None, r=10, alpha=100, n_epoch=15, beta=1e-3,
cutoff=500, n_user_items=None, model_out_root=None,
model_name='wrmf... |
import bot
class Module(bot.Module):
def __init__(self, config):
super().__init__(config)
self.file = None
if 'file' in self.config:
self.file = open(self.config['file'], 'a')
def print(self, *args):
print(*args)
if self.file is not None:
self.f... |
import numpy as np
import matplotlib.pyplot as plt
import os
import PIL.Image as Image
import torch
from torch.autograd import Variable
import torchvision.models as models
import torchvision.transforms as transforms
from deformation import ADef
from vector_fields import draw_vector_field
from write_results import wr... |
"""
Logit ratio analysis between excess mortality and covid deaths
- use covaraite idr_lagged
- pre-analysis getting prior
- cascade model infer location variation
"""
from typing import List, Dict, Union
from pathlib import Path
from scipy.optimize import LinearConstraint
import numpy as np
import pandas as pd
import... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from infrastructure.db.question_solution_schema import QuestionSolution
import logging
logger = logging.getLogger(__name__)
class QuestionSolutionRepositoryPostgres:
def add_question_solution(self, db, question_solution):
db.add(question_solution)
db.commit()
logger.info("Added new questi... |
# File: recordedfuture_consts.py
#
# Copyright (c) Recorded Future, Inc, 2019-2022
#
# This unpublished material is proprietary to Recorded Future. All
# rights reserved. The methods and techniques described herein are
# considered trade secrets and/or confidential. Reproduction or
# distribution, in whole or in part,... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.recover_virtual_disk_info_proto
import cohesity_management_sdk.models.recover_virtual_disk_params
class RecoverDisksTaskStateProto(object):
"""Implementation of the 'RecoverDisksTaskStateProto' model.
TODO: type mod... |
import re
from .site import main, Site
class Amazon(Site):
"""amazon.com"""
BASE_URL = 'https://www.amazon.com'
NAMES = {
'en': 'Amazon',
'ja-jp': 'Amazon',
'zh-cn': '亚马逊',
}
MIN_RATING = 1
MAX_RATING = 5
SEARCH_LOCALES = ['en-jp', 'en']
def info_url(self, id... |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from __future__ import with_statement
import os
import sys
# workaround on osx, disable kqueue
if sys.platform == "darwin":
os.environ['EVENT_NOKQUEUE'] = "1"
import gevent
from geven... |
# Learn more about testing at: https://juju.is/docs/sdk/testing
import unittest
from unittest.mock import Mock
from charm import MariadbCharm
from ops.model import ActiveStatus
from ops.testing import Harness
from charm import COMMAND
from unittest.mock import patch
class TestCharm(unittest.TestCase):
def setUp(... |
import gettext
from google.cloud import datastore
from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.chataction import ChatAction
from telegram.ext import CallbackContext
from pdf_bot.consts import LANGUAGE, LANGUAGES, USER
from pdf_bot.store import client
def send_... |
# events.py
# Copyright 2008 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""Results database Event panel class.
"""
import tkinter.messagebox
from ..core import resultsrecord
from ..core import ecfmaprecord
from ..core import filespec
from . import events_lite
class Events(events_lite.Events):
"""The Even... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import pdb
loc_gt = np.loadtxt('../../../../datasets/LogosInTheWild-v2/LogosClean/commonformat/ImageSets/top_only.txt', dtype=str)
np.random.seed(1)
X = loc_gt
def dist_from_arr(arr):
dist = np.array(np.unique(ar... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.12
# In conjunction with Tcl version 8.6
# Apr 15, 2018 05:51:30 AM
import sys
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = False
except I... |
import numpy as np
from utils import *
from keras.models import Model
from keras.layers import Dense, Input, Dropout, LSTM, Activation
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras.initializers import glorot_uniform
maxLen = 10
X_train, Y_train = read_csv("D... |
# Stopwatch colors
BLACK = 0x000000
WHITE = 0xFFFFFF
GRAY = 0x888888
LIGHT_GRAY = 0xEEEEEE
DARK_GRAY = 0x484848
ORANGE = 0xFF8800
DARK_ORANGE = 0xF18701
LIGHT_BLUE = 0x5C92D1
BLUE = 0x0000FF
GREEN = 0x00FF00
PASTEL_GREEN = 0x19DF82
SMOKY_GREEN = 0x03876D
YELLOW = 0xFFFF00
MELLOW_YELLOW = 0xF4ED06
RED = 0xFF0000
DARK_RE... |
#From https://gist.github.com/EndingCredits/b5f35e84df10d46cfa716178d9c862a3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state... |
from collections import OrderedDict as odict
import numpy as np
import pandas as pd
import maspy.peptidemethods
import maspy.proteindb
def write_evidence_table(ev, path):
""" Write an updated evidence table file. """
columns = [
'Sequence', 'Modified sequence', 'Sequence start', 'Sequence end',
... |
#!/usr/bin/env python2
import os
import pkgutil
import importlib
import fwsynthesizer
from fwsynthesizer.utils import *
FRONTENDS = [ x[1] for x in pkgutil.iter_modules(__path__) ]
class Frontend:
"Frontend object"
def __init__(self, name, diagram, language_converter,
query_configuration=Non... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .gpr import GPR, LRAGPR
__all__ = [
'GPR', 'LRAGPR'
]
|
import asyncio
from typing import Any, Union
from pydantic.main import BaseModel
from .event_notifier import EventNotifier, Subscription, TopicList, ALL_TOPICS
from broadcaster import Broadcast
from .logger import get_logger
from fastapi_websocket_rpc.utils import gen_uid
logger = get_logger('EventBroadcaster')
# ... |
# Copyright 2012 IBM Corp.
#
# 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 t... |
import argparse
import template
import os.path
import easydict
### See option.py for detailed information.
args = easydict.EasyDict({
'debug': False,
'template': '.',
'degradation': False,
# Hardware specifications
'n_threads': 0,
'cpu': False,
'n_GPUs': 1,
'seed': 1,
# Data sp... |
# -*- coding: utf-8 -*-
# Copyright Noronha 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 applica... |
import unittest
import numpy as np
import numpy.testing as npt
import wisdem.towerse.tower_struct as tow
from wisdem.towerse import RIGID
class TestStruct(unittest.TestCase):
def setUp(self):
self.inputs = {}
self.outputs = {}
self.discrete_inputs = {}
self.discrete_outputs = {}
... |
# Generated by Django 3.2 on 2021-05-12 14:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_alter_post_content'),
]
operations = [
migrations.AddField(
model_name='post',
name='snippet',
... |
'''
Utility function for generating tubular mesh from a central line
using a segment profile.
'''
from __future__ import division
import math
from opencmiss.utils.zinc.field import findOrCreateFieldCoordinates, findOrCreateFieldTextureCoordinates
from opencmiss.zinc.element import Element
from opencmiss.zinc.field impo... |
# %%
import requests
# %%
def get_string_net(genes, score=800):
"""Query STRINGdb interactions endpoint"""
string_api_url = "https://string-db.org/api"
output_format = "tsv-no-header"
method = "network"
request_url = "/".join([string_api_url, output_format, method])
params = {
"ident... |
from sharedData import *
changeRegister_api = Blueprint('changeRegister_api', __name__)
# users registers
@changeRegister_api.route('/changeregister', methods=['GET', 'POST'])
def changeRegister():
global usersDataOnline
print("////////////////////////////////////////")
print("comeca change register")
... |
import pytest
from seleniumbase import BaseCase
from selenium.webdriver.common.keys import Keys
from qa327_test.conftest import base_url
from unittest.mock import patch
from qa327.models import db, User
from werkzeug.security import generate_password_hash, check_password_hash
"""
This file defines all unit tests for ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import sys
import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt
import cv2
import ellipse
DEBUG_IMAGES = []
def debug_show(name, src):
global DEBUG_IMAGES
filename = 'debug{:02d}_{}.pn... |
import unittest
from visuanalytics.tests.analytics.transform.transform_test_helper import prepare_test
class TestTransformLength(unittest.TestCase):
def setUp(self):
self.data = {
"list": ["Canada", "Argentina", "Cyprus", "Schweden", "Norway", "USA", "Germany", "United Kingdom", "Z"],
... |
from django.core.management.base import BaseCommand
from parkings.importers import PaymentZoneImporter
class Command(BaseCommand):
help = 'Uses the PaymentZoneImporter to import payment zones.'
def add_arguments(self, parser):
parser.add_argument(
'address',
type=str,
... |
import requests
base_url_all_pkms = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/%ID%.png'
if __name__ == '__main__':
for i in range(1, 899):
url = base_url_all_pkms.replace('%ID%', str(i))
pkm_sprite = requests.get(url=url)
with open('../pokemons/sprites/' + s... |
"""
File: subsets.py
Name:
-------------------------
This file prints all the sub-lists on Console
by calling a recursive function - list_sub_lists(lst).
subsets.py is a famous LeetCode Medium problem
"""
def main():
"""
LeetCode Medium Problem
"""
list_sub_lists(['a', 'b', 'c', 'd', 'a'])
def list_... |
#validation DS
server_fields = {
"match_keys": "['id', 'mac_address', 'cluster_id', 'ip_address', 'tag', 'where']",
"obj_name": "server",
"primary_keys": "['id', 'mac_address']",
"id": "",
"host_name": "",
"mac_address": "",
"ip_address": "",
"parameters": """{
'int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.