content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from __future__ import annotations
from datetime import datetime
from jsonclasses import jsonclass, types
from jsonclasses_pymongo import pymongo
@pymongo
@jsonclass(class_graph='linked')
class LinkedBomb:
id: str = types.readonly.str.primary.mongoid.required
name: str
soldiers: list[LinkedSoldier] = type... | python |
"""
rvmath.base
~~~~~~~~~~~
:copyright: 2021 by rvmath Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import annotations
import collections
import itertools as it
import numbers
import operator
import secrets
import typing as ty
from dataclasse... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 13:26:57 2018
@author: Fall
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5,5,1000)
y = np.sin(x)
plt.plot(x, y, label="objective")
plt.plot(x, 0*x+0.5, color="r", linestyle="--", label="constraint")
plt.fill_between(x... | python |
import os
import time
import argparse
import logging
from dirtositemap import DirToSitemap
from config import *
from sitemaptree import SitemapTree
def cmp_file(f1, f2):
st1 = os.stat(f1)
st2 = os.stat(f2)
# compare file size
if st1.st_size != st2.st_size:
return False
b... | python |
###
# Copyright (c) 2005, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... | python |
#!/usr/bin/python2
import rospy
import cv_bridge
from cv_bridge import CvBridge
import cv2
import rospy
import numpy as np
from sensor_msgs.msg import CompressedImage
from crazyflie.msg import CFData
# from crazyflie.msg import CFImage
from crazyflie.msg import CFCommand
from crazyflie.msg import CFMotion
import time... | python |
#!/usr/bin/python
"""
(C) Copyright 2019 Intel Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... | python |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
'''Generate DV code for an IP block'''
import logging as log
import os
import sys
from collections import defaultdict
from typing import Dict, List, Union, Optional
import... | python |
import cocotb
from lib.util import assertions
from lib.cycle import wait, clock
@cocotb.test()
def memory_address_register(dut):
def assert_o_address(value, error_msg):
"""Check the output address"""
assertions.assertEqual(dut.o_address.value.binstr, value, error_msg)
# Test initialization
... | python |
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
from modules.networks import LinearGaussianTree, TriResNet, ASVIupdate
from modules.models import ColliderModel, MeanField, GlobalFlow, MultivariateNormal
from modules.distributions import NormalDistribu... | python |
from django.contrib import admin
from .models import ScrumyUser, ScrumyGoals, GoalStatus
# Register your models here.
myModels = [ScrumyUser, ScrumyGoals, GoalStatus]
admin.site.register(myModels)
| python |
import re
from itertools import izip_longest
def percent(num, den):
return '%2.0f%%' % ((float(num)/den) * 100)
def parse(fname, level=2):
f = file(fname)
c = f.read()
f.close()
num_lines = len(c.split('\n'))
headings = []
print 'num lines', num_lines
regexp = '#{1,%s}\s' % level
f... | python |
import glob
import os
from time import sleep, ctime
PATH = r"C:\Users\timmo\Downloads\*"
list_of_files = glob.glob(PATH)
latest_file = max(list_of_files, key=os.path.getctime)
latest_mod = os.path.getctime(latest_file)
latest_mod = ctime(latest_mod)
#latest_mod = datetime.fromtimestamp(latest_mod).strftime('%Y-%m-%d ... | python |
"""
The MIT License (MIT)
Copyright (c) 2015-2019 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, copy, modify, merge, pu... | python |
import FWCore.ParameterSet.Config as cms
from ..modules.hltEgammaCandidatesL1Seeded_cfi import *
from ..modules.hltEgammaHGCALIDVarsL1Seeded_cfi import *
from ..modules.hltEgammaHoverEL1Seeded_cfi import *
HLTPhoton187L1SeededTask = cms.Task(
hltEgammaCandidatesL1Seeded,
hltEgammaHGCALIDVarsL1Seeded,
hltE... | python |
#!/usr/bin/env python3
# pylint: disable=C0103
"""Gets coordination environment and corresponding CSM."""
from pymatgen import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.analysis.chemenv.coordination_environments\
.coordination_geometry_finder import LocalGeometryFinder
fro... | python |
from .conv import *
from .cell import *
from .mix_ops import *
from .prune import *
from .ops import *
| python |
import binascii
import binance.crypto
import binance.message
from .signature import *
from .transaction import *
class TransactionEncoder(object):
def __init__(self, wallet, memo="", source=0, data=None):
self.wallet = wallet
self.memo = memo
self.source = source
self.data = data
... | python |
from pythonforandroid.recipe import CompiledComponentsPythonRecipe
from os.path import dirname, join
class CryptographyRecipe(CompiledComponentsPythonRecipe):
name = 'cryptography'
version = '1.4'
url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
depends = [('python2', 'python3cryst... | python |
"""empty message
Revision ID: 096057bb3435
Revises: 2daaf569f64d
Create Date: 2021-09-19 01:29:38.703707
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '096057bb3435'
down_revision = '2daaf569f64d'
branch_labels = None
depends_on = None
def upgrade():
# ... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 27 12:05:05 2014
@author: dreymond
"""
import json
import pickle
import os
import codecs
#import bs4
from Patent2Net.P2N_Lib import LoadBiblioFile, Decoupe, UnNest3, UrlInventorBuild, UrlApplicantBuild, UrlIPCRBuild
from Patent2Net.P2N_Config import LoadConfig
import ... | python |
from mamba import description, before, context, it, after
from expects import equal, expect, be_none
from os import (
environ,
getpid,
)
import pika
from infcommon import logger
from infcommon.serializer import factory as serializer_factory
from infrabbitmq.rabbitmq import (
RabbitMQClient,
DIRECT_EX... | python |
import logging
import os
import turnip_exchange_tool.gateways.turnip_exchange as source
from turnip_exchange_tool.gateways.db import Sqlite3Db
from turnip_exchange_tool.models.island import Island
_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(format=_format, level=logging.DEBUG)... | python |
from flask import render_template, request, redirect, url_for, session, escape, send_from_directory, current_app
from flask.ext.login import current_user
from mathsonmars.models import db
from mathsonmars.extensions import cache
from mathsonmars.marslogger import logger
from mathsonmars.main import main_view
from maths... | python |
import json
from dataclasses import asdict
from typing import Dict, List, Tuple, Type
from fractal.core.repositories import Entity
from fractal.core.repositories.inmemory_repository_mixin import InMemoryRepositoryMixin
from fractal.core.utils.json_encoder import EnhancedEncoder
class ExternalDataInMemoryRepositoryMi... | python |
from request_manager import app, db
from flask import render_template, redirect, url_for
from request.form import RequestForm
from product.models import Product
from client.models import Client
from request.models import RequestModel
@app.route('/')
@app.route('/index')
def index():
return redirect(url_for('reques... | python |
#!/usr/bin/env python
"""
Unit test for the grasping_handler_server.py.
NOTE: This should be run via 'rosrun grasping test_grasping_handler_server.py' and NOT with 'python test_grasping_status_server.py'.
WARNING: These test requires a connection to Robot DE NIRO
Author: John Lingi
Date: 05/18
"""
import rospy
impo... | python |
# coding: utf-8
from proxy_spider.items import Proxy
from proxy_spider.spiders import _BaseSpider
from service.proxy.functions import exceed_check_period, valid_format
class CheckerSpider(_BaseSpider):
"""
Check proxy's availability and anonymity.
"""
name = 'checker'
# allowed_domains = ['*']
... | python |
import argparse
from datetime import datetime
import os
import torch
import torch.nn as nn
import torch.utils.data
from model import Model
from dataset import Dataset
from tqdm import tqdm
from sklearn.metrics import confusion_matrix
parser = argparse.ArgumentParser(description='Train a CNN to classify image patche... | python |
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from products.models import Product
from cart.models import ShippingDetails
# Create your ... | python |
# coding: utf-8
#
# This code is part of dqmc.
#
# Copyright (c) 2022, Dylan Jones
#
# This code is licensed under the MIT License. The copyright notice in the
# LICENSE file in the root directory and this permission notice shall
# be included in all copies or substantial portions of the Software.
import logging
# =... | python |
import time
from multiprocessing.dummy import freeze_support
from pprint import pprint
from flowless import TaskState, RouterState, ChoiceState, FlowRoot, save_graph, QueueState
from flowless.deploy import deploy_pipline
from flowless.states.router import ParallelRouter
from flowless.demo_states import ModelClass, T... | python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
send.py will send a single messages to the queue.
"""
# Pika is a pure-Python implementation of the AMQP 0-9-1 protocol
import pika
# guest user can only connect via localhost
#credentials = pika.PlainCredentials('guest', 'guest')
credentials = pika.PlainCredentials('... | python |
from re import compile as re_compile, error as re_error, escape
from sys import stdout
from ..constant.colors import *
__all__ = [
'black', 'dark_blue', 'dark_green', 'dark_aqua', 'dark_red', 'dark_purple',
'gold', 'gray', 'dark_gray', 'blue', 'green', 'aqua', 'red', 'light_purple',
'yellow', 'white',
... | python |
# import packages
import bs4
import requests
from bs4 import BeautifulSoup
# get soup object
def get_soup(text):
return BeautifulSoup(text, "lxml", from_encoding='utf-8')
# extract company
def extract_company(div):
try:
return (div.find('div', attrs={'class', 'job-result-card__contents'}).find('h4... | python |
#!/usr/bin/env python
"""packt.py: Grab the daily free book claim from Packt Press.
This will run under Python 2.7 and 3.4 with minimum dependencies.
The goals was the most simplistic code that will function. The
script can be run from cron.
Replace the two lines with username/email and password with you... | python |
# coding=utf-8
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
# Modules
{
"module_name": "Case Management",
"color": "grey",
"icon": "octicon octicon-organization",
"type": "module",
"label": _("Case Management")
},
{
"module_name": "CPBNs",
"color"... | python |
#!/usr/bin/env python
import argparse
import gzip
from contextlib import ExitStack
import pysam
from statistics import mean, median
argparser = argparse.ArgumentParser(description = 'Aggregate depth information (output as JSON) from individual depth files (generated using SAMtools mpileup).')
argparser.add_argument(... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: result_to_latex.py
import os, argparse, json, math
import logging
TEMPLATE = r"""\begin{table*}[tb]
\centering
\caption{Chaos Engineering Experiment Results on HedWig}\label{tab:resultsOfHedwig}
\setcounter{rowcount}{-1}
\begin{tabular}{@{\makebox[3em][r]{\stepcou... | python |
from socket import *
class ChatServer:
def __init__(self, host, port):
#startvars
self.PORT = port
self.HOST = host
self.RECV_BUFFER = 4096
self.CONNECTION_LIST = []
#connection
self.server_socket = socket(AF_INET, SOCK_STREAM)
self.server_so... | python |
from collections import defaultdict
from itertools import chain
from typing import Collection, Dict, Set, AnyStr, Iterable, TextIO
import pandas as pd
from pandas import Series, DataFrame
import jinja2 as j2
from burdock.core.variable import DaikonVariable, consts_from_df, vars_from_df
from burdock.expander import E... | python |
r"""
Gcd domains
"""
#*****************************************************************************
# Copyright (C) 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*******************... | python |
import copy
import glob
import os
import numpy as np
import torch.utils.data as data
import torchvision as tv
from PIL import Image
from torch import distributed
from .utils import Subset, group_images
# Converting the id to the train_id. Many objects have a train id at
# 255 (unknown / ignored).
# See there for mo... | python |
import datetime
import json
import yaml
import random
import string
def get_random_name(length=20):
store = string.ascii_letters + string.digits
return random.choice(string.ascii_letters) + ''.join([random.choice(store) for i in range(length - 1)])
def read_credentials(filename):
with open(filename) as ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Python for AHDA.
Part 1, Example 4.
"""
# Simple list
words = ['Mary', 'had', 'a', 'little', 'lamb']
# words = ('Mary', 'had', 'a', 'little', 'lamb')
print(words)
print(words[1])
words[3] = 'big'
print(words)
| python |
from ..utils import SyncClient, __version__
from .bucket import SyncStorageBucketAPI
from .file_api import SyncBucketProxy
__all__ = [
"SyncStorageClient",
]
class SyncStorageClient(SyncStorageBucketAPI):
"""Manage storage buckets and files."""
def __init__(self, url: str, headers: dict[str, str]) -> No... | python |
import tensorflow as tf
import numpy as np
import time
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "4"
from tensorflow.python.eager import tape
class FakeData(object):
def __init__(self, length):
super(FakeData, self).__init__()
self.length = length
self.X_train = np.random.random((224... | python |
import json
import logging
from django.utils.translation import ugettext_lazy as _
from requests import RequestException
from connected_accounts.conf import settings
from connected_accounts.provider_pool import providers
from .base import OAuth2Provider, ProviderAccount
logger = logging.getLogger('connected_account... | python |
import argparse
import difflib
import re
import sys
from ssort._exceptions import UnknownEncodingError
from ssort._files import find_python_files
from ssort._ssort import ssort
from ssort._utils import (
detect_encoding,
detect_newline,
escape_path,
normalize_newlines,
)
def main():
parser = argp... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: thunderstorm.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _sym... | python |
import json
import os
def dump_json(o: object, filename: str) -> None:
with open(filename, 'w', encoding='utf8') as f:
json.dump(o, f, ensure_ascii=False)
def load_json(filename: str):
with open(filename, 'r', encoding='utf8') as f:
return json.load(f)
def setup_django_pycharm():
os.en... | python |
from django.test import TestCase
from . import *
class AbstractFormModelTestCase(TestCase):
def setUp(self):
pass
def create_form(self):
return AbstractFormModel.objects.create()
def test_form_creation(self):
print("Testing if running")
f = self.create_form()
l =... | python |
"""
REST API Documentation for TheOrgBook
TheOrgBook is a repository for Verifiable Claims made about Organizations related to a known foundational Verifiable Claim. See https://github.com/bcgov/VON
OpenAPI spec version: v1
Licensed under the Apache License, Version 2.0 (the "License");
... | python |
import pygments
import pygments.lexers
from pygments.token import Token
import PIL, PIL.Image, PIL.ImageFont, PIL.ImageDraw
from PIL.ImageColor import getrgb
import sys, os
import subprocess, re
font = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'font.pil')
class StyleDict(dict):
''' Store color info... | python |
class NextcloudRequestException(Exception):
def __init__(self, request=None, message=None):
self.request = request
message = message or f"Error {request.status_code}: {request.get_error_message()}"
super().__init__(message)
class NextcloudDoesNotExist(NextcloudRequest... | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\vet\vet_clinic_zone_director.py
# Compiled at: 2017-11-06 20:04:35
# Size of source mod 2**32: 27524... | python |
#coding:utf-8
###################################################
# File Name: export.py
# Author: Meng Zhao
# mail: @
# Created Time: 2019年11月11日 星期一 16时03分43秒
#=============================================================
import os
import sys
import json
import shutil
import tensorflow as tf
import modeling
from ... | python |
import os
from rsqueakvm.error import PrimitiveFailedError
from rsqueakvm.plugins.plugin import Plugin
from rsqueakvm.primitives import index1_0
from rsqueakvm.util.system import IS_WINDOWS
class UnixOSProcessPlugin(Plugin):
def is_enabled(self):
return Plugin.is_enabled(self) and not IS_WINDOWS
plugin... | python |
from sklearn.ensemble import GradientBoostingRegressor
from deathbase.supervised.regression.base import BaseRegressor
class GradientBoosting(BaseRegressor):
def __init__(self, *args, **kwargs):
regressor = GradientBoostingRegressor(verbose=1)
super().__init__(regressor, *args, **kwargs) | python |
# Copyright 2019 Microsoft Corporation
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager
@resources.register('postgresql-server')
class PostgresqlServer(ArmResourceManager):
"""PostgreSQL ... | python |
from math import *
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from gcparser import get_parsed_struct
def Hill_Function_R(Kd,N,C):
# Hill function for modeling repressors
hill=1/(1+(N/Kd)**C)
# print hill
return hill
def Hill_Function_A(Kd,N,C):
# Hill fun... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Tridots Tech Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
# from _future_ import unicode_literals
import frappe
import frappe.utils
import json
from frappe import _
def g... | python |
"""
Exceptions for conditions app
"""
class TreatmentTooRecentError(Exception):
pass
class TreatmentAltConflict(Exception):
pass
| python |
from __future__ import annotations
import logging
import os
import pickle
from collections import Counter
from functools import partial
from itertools import groupby
from operator import itemgetter
from typing import Any, Dict, Iterator, List, Optional, Tuple
import click
import h5py
import numba
import numpy as np
f... | python |
import sys
sys.path.append('../')
from Normalizer.Normalizer import Normalizer
import unittest
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
class TestNormalizer(unittest.TestCase):
normalizer = Normalizer()
test_data = [ 61.19499969, 57.31000137, 56.09249878, 61.72000122... | python |
from typing import List
from local_packages.binary_tree import TreeNode
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrderBottom(self, root: Tr... | python |
import os
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from PIL import Image
from tqdm import tqdm
wb = Workbook()
sheet = wb.active
def rgb_to_hex(rgb):
return '%02x%02x%02x' % rgb
for file in os.listdir():
if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith... | python |
import os
import numpy as np
import importlib
SilhouetteDetector = importlib.import_module('SilhouetteDetector')
np.random.seed(0)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Generate artificial videos with one subject')
parser.add_argument('--dataset', type... | python |
# -*- coding: utf-8 -*-
from numpy import *
from datetime import datetime, timedelta
from dateutil.relativedelta import *
import os
import re
import codecs
import pandas as pd
import scipy.io.netcdf as spnc
from ecmwfapi import ECMWFDataServer
import time_tools as tt
import geo_tools as gt
import downlo... | python |
from robot.api.parsing import (
Token,
ModelTransformer,
SectionHeader,
EmptyLine
)
from robot.parsing.model.statements import Statement
import click
class MergeAndOrderSections(ModelTransformer):
"""
Merge duplicated sections and order them.
Default order is: Comments > Settings > Variab... | python |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize('harmony.pyx'))
| python |
from logbook import Logger, StreamHandler, TimedRotatingFileHandler
from logbook.more import ColorizedStderrHandler
import logbook
import socket
import uuid
import sys
import fire
import os
def logger(name='LOGBOOK', log_path='', file_log=False):
logbook.set_datetime_format('local')
ColorizedStderrHandler(bubble=Tr... | python |
import test_reader as FR
if __name__ == "__main__":
extra = FR.Pair()
extra.first = '1'
extra.second = '2'
buf = extra.to_fbs()
extra1 = FR.Pair(buf)
acc = FR.Account()
acc.langs.append(FR.test_fbs.Language.Language.CHT)
acc.langs.append(FR.test_fbs.Language.Language.CHS)
ac... | python |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019, Nigel Small
#
# 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... | python |
import logging
import random
import string
import sys
import textwrap
import time
import typing
from contextlib import contextmanager
from datetime import datetime, timedelta
from functools import lru_cache, wraps
import flask
from util.config_utils import iris_prefix
def cls_by_name(fully_qualified_classname):
... | python |
import sys
from itertools import islice, izip
def parse(lines):
return [int(line.split(" ")[-1]) for line in lines]
def generator(startValue, factor, multiple):
prevValue = startValue
while True:
prevValue = ( factor * prevValue ) % 2147483647
if prevValue % multiple == 0:
yiel... | python |
import sys
import random
import helptext
from time import sleep
from threading import Timer
from mbientlab.metawear import MetaWear, libmetawear, parse_value
from mbientlab.metawear.cbindings import *
from mbientlab.warble import *
from resizable import *
if sys.version_info[0] < 3:
import Tkinter as Tk
impor... | python |
real_value = float(input("enter real value(이론값): ")) #참값
test_value = float(input("enter test value: ")) #실험값
err = abs(real_value - test_value) / real_value
print(f"err = {err}")
| python |
# Copyright 2010 Gregory L. Rosenblatt
# 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 in wr... | python |
# 11.4. Dictionary methods
"""
Dictionaries have a number of useful built-in methods. The following table
provides a summary and more details can be found in the Python Documentation.
Method
Parameters
Description
keys
none
Returns a view of the keys in the dictionary
values
none
Returns a view of the values ... | python |
from abc import ABC, abstractmethod
import pandas as pd
class Interpolator(ABC):
@abstractmethod
def get_approximate_value(self, x: float, table: pd.DataFrame) -> float:
raise NotImplementedError
| python |
"""
Logging module.
"""
import logging
class Logger:
"""
Logger helper.
"""
loggers = {}
level = logging.WARNING
def __init__(self, logger):
self.__level = Logger.level
self.__logger = logging.getLogger(logger)
# set formatter
#formatter = logging.Formatter('[... | python |
"""Test prsw.api.looking_glass."""
import pytest
from datetime import datetime
from typing import Iterable
from unittest.mock import patch
from .. import UnitTest
from prsw.api import API_URL, Output
from prsw.stat.looking_glass import LookingGlass
class TestLookingGlass(UnitTest):
RESPONSE = {
"messag... | python |
from django.urls import path, include
# from django.conf.urls import include, url
# from .views import TestViewSet
from .views import *
from rest_framework import routers
router = routers.DefaultRouter()
router.register('task_list', TestViewSet, basename="task_list")
router.register('Machine', MachineViewSet, basenam... | python |
from utils.KTS.cpd_auto import *
| python |
class City:
'''
This class will hold a city in terms of its
x and y coordinates
@author Sebastian Castro
'''
def __init__(self, x, y):
# Holds the x and y components
self.x = x
self.y = y
self.point = (x, y)
def __str__(self):
return f'Ci... | python |
import os
# Directory Config
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
DB_DIR = os.path.join(ROOT_DIR, 'db')
# Regexes
COURSE_NAME_PATTERN = r'[FD]0*(\d+\w*)\.?'
DAYS_PATTERN = f"^{'(M|T|W|Th|F|S|U)?'*7}$"
# Scraped table headers (for scrape_term.py)
HEADERS = (
'course',
'CRN',
'desc',
'... | python |
#!/usr/bin/env python3
# coding:utf-8
import unittest
import zencad
#from PyQt5.QtWidgets import *
#from PyQt5.QtCore import *
#from PyQt5.QtGui import *
#from zencad.gui.settingswdg import SettingsWidget
#qapp = QApplication([])
class WidgetsTest(unittest.TestCase):
def test_segment_probe(self):
pass... | python |
import numpy as np
import tensorflow as tf
# N, size of matrix. R, rank of data
N = 100
R = 5
# generate data
W_true = np.random.randn(N,R)
C_true = np.random.randn(R,N)
Y_true = np.dot(W_true, C_true)
Y_tf = tf.constant(Y_true.astype(np.float32))
W = tf.Variable(np.random.randn(N,R).astype(np.float32))
C = tf.Varia... | python |
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
input = []
with open(os.path.join(script_dir, "input.txt"), "r") as file:
questionaire = {}
for line in file:
if (line.strip('\n') != ""):
if "People" in questionaire:
questionaire["People"] += 1
else:
questionaire["... | python |
from distutils.core import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pymp4parse',
version='0.3.0',
packages=[''],
url='https://github.com/use-sparingly/pymp4parse... | python |
import scrapy
class ScrapeTableSpider(scrapy.Spider):
name = 'jcs'
def start_requests(self):
urls = [
'https://en.wikipedia.org/wiki/List_of_schools_in_Singapore',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, respon... | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
# Copyright (c) 2017 Thomas P. Robitaille.
#
# Asclepias Broker is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Asclepias Broker."""
from __future__ import absolute_import, print... | python |
#
# Copyright (C) 2020 CESNET.
#
# oarepo-fsm is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""OArepo FSM library for record state transitions."""
from flask import url_for
from invenio_records_rest.links import default_links_factor... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bldcontrol', '0006_brlayer_local_source_dir'),
]
operations = [
migrations.AlterField(
model_name='brlayer',
... | python |
"""
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distanc... | python |
import difflib
import bs4 as bs
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
def parse_hocr(search_terms=None, hocr_file=None, regex=None):
"""Parse the hocr file and find a reasonable bounding box for each of the strings
in search_terms. Return a dictionary with va... | python |
#############################################################################
##
## Copyright (C) 2019 The Qt Company Ltd.
## Contact: http://www.qt.io/licensing/
##
## This file is part of the Qt for Python examples of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD lic... | python |
from pbge.plots import Plot
import game
import gears
import pbge
import random
from game import teams
# ***************************
# *** MECHA_ENCOUNTER ***
# ***************************
#
# Elements:
# LOCALE: The scene where the encounter will take place
# FACTION: The faction you'll be fighting; may b... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.