text stringlengths 2 999k |
|---|
################################################################################
# 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... |
# priceIndexToKafkaRealtime.py
import requests
import time
from kafka import SimpleProducer, KafkaClient
# Connect to Kafka
kafka = KafkaClient('localhost:9092')
producer = SimpleProducer(kafka)
# Assign a topic
topic = 'bitcoin-realtime'
# Send message
while 1:
jsonFile = requests.get("https://api.coindesk.com... |
#!/usr/bin/env python3
# -*- encoding: utf8 -*-
# Example: python -m scripts.glyph_model_convert FILE1 FILE2
import sys
import json
from importlib import import_module
from progressive.bar import Bar
sys.path.append('src/cv')
GlyphModel = import_module('glyph_model').GlyphModel
with open(sys.argv[1], 'r') as in_fp, o... |
#!/usr/bin/env python3
from flask import Flask, Blueprint
from prefix2as.views import prefix2as
def create_app():
app = Flask(__name__)
try:
app.config.from_pyfile('../prefix2as.conf')
except FileNotFoundError as exc:
app.logger.critical("'../prefix2as.conf' is not found.")
raise FileNotFoundError(exc)
tr... |
# _ _ _
# _____| |__ ___ _ __ _ __(_| |___ _ _
# (_-/ _` / _/ _ | ' \| '_ | | / -_| '_|
# /__\__,_\__\___|_|_|_| .__|_|_\___|_|
# |_|
# Copyright (c) 2013-2020 transentis management & consulting. All rights reserved.
#
import numpy as np
from scipy.interpolate import... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 required by appli... |
"""
Django settings for mangepicfudan project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from p... |
import cv2
import numpy as np
"""
Module with methods designed to manipulate Rectangular tuples (x, y, w, h).
"""
def draw_rectangles(frame, rect, thickness = 1):
"""
Draws rectangles onto frame.
"""
if rect is None: return frame
tmp = frame.copy()
for r in rect:
if r is None: continue
tmp = r.draw_rectang... |
from django.contrib import admin
from onadata.apps.logger.models import XForm
class FormAdmin(admin.ModelAdmin):
exclude = ('user',)
list_display = ('id_string', 'downloadable', 'shared')
# A user should only see forms that belong to him.
def get_queryset(self, request):
qs = super(FormAdmi... |
##############################################################################
#
# Copyright (c) 2012 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
""" A neural chatbot using sequence to sequence model with
attentional decoder.
This is based on Google Translate Tensorflow model
https://github.com/tensorflow/models/blob/master/tutorials/rnn/translate/
Sequence to sequence model by Cho et al.(2014)
Created by Chip Huyen as the starter code for assignment 3,
cla... |
import NaiveBayes
import sys
import os
def main(argv):
testNaiveBayesOnDiabetesDataset()
def testNaiveBayesOnDiabetesDataset():
observation = formatObservation("1,85,66,29,0,26.6,0.351,31")
classifier = getTrainedClassifierOnDiabetesDataset()
pred, prob = classifier.predict(observation, "Outcome")
... |
import os, sys
from authenticate import authorize
from googleapiclient.http import MediaFileUpload
def uploadFile(filePath, service, par_id):
"""
Uploads the content of a file to the given directory id.
"""
# Uploads the file under the directory pointed by par_if
metadata = {
'name' : os.p... |
import socket
import select
import queue as Queue
from request import Request
from response import Response, DefaultResponse
class Server:
inputs = []
outputs = []
messages = {}
routes = {}
donotkill = False
def __init__(self,port=2145):
self.sock = socket.socket(socket.AF_INET,s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-09-28 13:27
from __future__ import unicode_literals
import account.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0010_auto_20170914_1920'),
]
operations = [
... |
import _plotly_utils.basevalidators
class DtickValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(
self, plotly_name='dtick', parent_name='layout.scene.xaxis', **kwargs
):
super(DtickValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import logging
import os
from collections import defaultdict
from typing import Any, Dict, List, Optional, Tuple
import ujson as js... |
from datetime import datetime
from django.conf import settings
from django.shortcuts import render
from django.http import HttpRequest
from app.models import Department, Employee, Position
from django.http import HttpResponseRedirect
from django.views.generic.list import ListView
from app.adminpanel.employee.forms imp... |
# Lint as: python2, python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... |
#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#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 l... |
#!/usr/bin/env python
__author__ = "Evripidis Gkanias"
__copyright__ = "Copyright (c) 2019, Insect Robotics Group," \
"Institude of Perception, Action and Behaviour," \
"School of Informatics, the University of Edinburgh"
__credits__ = ["Evripidis Gkanias"]
__license__ = "MIT"
__version... |
import pytest
import numpy as np
from conftest import fixed_shape_backend_params, variable_shape_backend_params
from itertools import permutations
def assert_equal(arr, arr2):
assert np.array_equal(arr, arr2)
assert arr.dtype == arr2.dtype
class TestColumn(object):
@pytest.mark.parametrize('name', [
... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
import b3
__all__ = ['Priority']
class Priority(b3.Composite):
def __init__(self, children=None):
super(Priority, self).__init__(children)
self.Name = '*Priority*'
def tick(self, tick):
self.Cost = 0
for node in self.children:
status = node._execute(tick)
#... |
from django.urls import path
from code_of_conduct.views import CodeOfConductView
urlpatterns = [
path(
'<str:owner>/<str:repo>/<str:token_auth>/',
CodeOfConductView.as_view()
)
]
|
import komand
from .schema import DeleteSiteInput, DeleteSiteOutput, Input
# Custom imports below
from komand_rapid7_insightvm.util import endpoints
from komand_rapid7_insightvm.util.resource_helper import ResourceHelper
class DeleteSite(komand.Action):
def __init__(self):
super(self.__class__, self).__i... |
# -*- coding: utf-8 -*-
import time
import requests
from libs.pymongodb import pymongodb
from libs import decorators
from libs import utils
class AddNewPosts(object):
def __init__(self):
self.mongo = pymongodb.MongoDB('btt')
self.documents = self.mongo.find({}, 'en_altcoins')
self.form_u... |
from __future__ import unicode_literals
import django_filters
from django.db.models import Q
from dcim.models import Site
from extras.filters import CustomFieldFilterSet
from tenancy.models import Tenant
from utilities.filters import NumericInFilter
from .constants import CIRCUIT_STATUS_CHOICES
from .models import Pr... |
from __future__ import division
from math import log, ceil, floor
import os
import re
from subprocess import Popen, PIPE
import sys
from tempfile import TemporaryFile
from warnings import warn
import json
try:
import audioop
except ImportError:
import pyaudioop as audioop
if sys.version_info >= (3, 0):
... |
import os
import subprocess
from jtalkbot import openjtalk
##### チェック用モジュール #####
# ボイスチャンネルにコマンド実行者がいるか判定する
def vc_check(m, b, a):
return m.voice is not None # bool(ctx.author.voice)でもOK
# botが発言中か判定する
def playing_check(m):
if m.guild.voice_client:
return m.guild.voice_client.is_playing() is False
... |
import _plotly_utils.basevalidators
class TickwidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name='tickwidth',
parent_name='contourcarpet.colorbar',
**kwargs
):
super(TickwidthValidator, self).__init__(
plotly_name=... |
# greaseweazle/codec/ibm/mfm.py
#
# Written & released by Keir Fraser <keir.xen@gmail.com>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
import copy, heapq, struct, functools
import itertools as it
from bitarray imp... |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from typing import Any, Tuple, TypeVar
from azure.core.polling import AsyncLROPoller
from azure.core.polling.base_polling import (
OperationFailed,
... |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
from django.apps import AppConfig
class CfPConfig(AppConfig):
name = "pretalx.cfp"
def ready(self):
from . import permissions # noqa
from .phrases import CfPPhrases # noqa
default_app_config = "pretalx.cfp.CfPConfig"
|
from collections import UserList
from django import forms
from django.core.validators import RegexValidator
from django.db.models.fields import TextField
from django.forms.widgets import TextInput
from collections.abc import Iterable
class PathValue(UserList):
def __init__(self, value):
if isinstance(val... |
#!/usr/bin/env python3
"""Project Euler - Problem 55 Module"""
import pelib
# Limit 10000
# < 50 steps to turn into palindrome
LYCHREL_NUMBER_LIMIT = 10000
MAX_NR_STEPS_LYCHREL_TEST = 50
def is_lychrel(number):
"""Determines if number holds Lychrel-Property"""
if number >= LYCHREL_NUMBER_LIMIT:
rai... |
import requests
import json
from django.shortcuts import render, HttpResponse
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDo... |
import config
import trainer_step
def main():
cfg = config.Config(filenamequeue="../data/dataset/layout_1205.tfrecords")
t = trainer_step.Trainer(cfg)
t.fit()
if __name__ == "__main__":
main()
|
from biosimulators_utils.utils.identifiers_org import (
IdentifiersOrgNamespace,
InvalidIdentifiersOrgUri,
get_identifiers_org_namespaces,
get_identifiers_org_namespace,
validate_identifiers_org_uri,
)
import unittest
class IdentifiersOrgUtilsTestCase(unittest.TestCase):
def test_get_identifie... |
import logging
import os
from typing import Optional, Text, Union, List, Dict
from rasa import data
from rasa.core.domain import Domain, InvalidDomain
from rasa.core.interpreter import RegexInterpreter, NaturalLanguageInterpreter
from rasa.core.training.structures import StoryGraph
from rasa.core.training.dsl import S... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient, Recipe
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recip... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch.nn.functional as F
... |
__author__ = 'adelpozo'
from . import config |
"""
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
Example 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Example 2:
add(3... |
"""Shows the use of annotate without any type information.
The type information is extracted from the arguments passed
and the function is annotated and compiled at runtime.
"""
from pysph.cpy.api import annotate, Elementwise, wrap, get_config
import numpy as np
@annotate
def axpb(i, x, y, a, b):
xi = declare('d... |
#!python
#
# Copyright 2019 Codeplay Software Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use these files 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 o... |
# This file is part of PyOP2
#
# PyOP2 is Copyright (c) 2012, Imperial College London and
# others. Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... |
import copy
from core.expression import Equal, Plus, Times, Minus, Transpose, Inverse, \
Symbol, PatternDot, PatternStar, NList, Predicate
from core.functional import Constraint, Replacement, RewriteRule, match, replace
import core.properties as properties
from core.InferenceOfProperties im... |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test compact blocks (BIP 152).
Version 1 compact blocks are pre-segwit (txids)
Version 2 compact block... |
"""
Exports various fideslang objects for easier use elsewhere.
"""
from typing import Dict, Type, Union
# Export the Models
from .models import (
DataCategory,
DataQualifier,
DataSubject,
DataUse,
Dataset,
DatasetField,
Evaluation,
FidesModel,
Organization,
Policy,
PolicyR... |
import os
import numpy as np
import cv2
import time
import datetime
from utils import CFEVideoConf, image_resize
import glob
cap = cv2.VideoCapture(0)
frames_per_seconds = 20
save_path='saved-media/timelapse.mp4'
config = CFEVideoConf(cap, filepath=save_path, res='720p')
out = cv2.VideoWriter(save_pa... |
from .ss13status import SS13Status
def setup(bot):
bot.add_cog(SS13Status(bot)) |
# pip install cassandra-driver
from cassandra import AlreadyExists
from cassandra.cluster import Cluster
class CassandraWrapper:
def __init__(self, keyspace='lambda'):
self.cluster = Cluster(['127.0.0.1'], port=9042)
self.keyspace = keyspace
self._setup_db() # Create the keyspace
... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# (c) B.Kerler 2018-2021 MIT License
import logging
from mtkclient.Library.utils import LogBase, logsetup
from mtkclient.Library.gpt import gpt
class Partition(metaclass=LogBase):
def __init__(self, mtk, readflash, read_pmt, loglevel=logging.INFO):
self.mtk = mtk... |
# -*- coding: utf-8 -*-
"""
:author: 秋荏苒
:copyright: © 2019 by 秋荏苒 <nuanyang.44@gmail.com>.
:license: MIT, see LICENSE for more details.
"""
import os
import secrets
import click
# import sentry_sdk
from flask import Flask, render_template
from flask_login import current_user
from flask_sqlalchemy import ... |
from enum import Enum, auto
from .article_filter import ArticleFilter
from .existed_filter import ExistedFilter
from .min_datetime_filter import MinDateTimeFilter
from .post_type_filter import PostTypeFilter
class ArticleFilterType(Enum):
"""
Enum of all possible article filters
"""
min_datetime_fil... |
import os
import json
import sys
import time
import torch
from torch import nn
from torch import optim
import torchvision as tv
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
from PIL import Image
import numpy as np
EPS = 1e-6
ALPHA_RECONSTRUCT_IMAGE = 1
ALPHA_RECONSTRUCT_LATENT ... |
from setuptools import setup
# extract version from __init__.py
with open('trajnetbaselines/__init__.py', 'r') as f:
VERSION_LINE = [l for l in f if l.startswith('__version__')][0]
VERSION = VERSION_LINE.split('=')[1].strip()[1:-1]
setup(
name='trajnetbaselines',
version=VERSION,
packages=[
... |
import numpy as np
from rapt import Re, B0
from scipy.interpolate import RegularGridInterpolator
class _Field:
"""
The superclass for fields. Not used directly, but subclassed. All field-
related data and methods are defined in field objects.
Attributes
----------
gradientstepsize : float
... |
import util
import numpy as np
import random
from transformers import BertTokenizer, AutoTokenizer
import os
from os.path import join
import json
import pickle
import logging
import torch
import itertools
logger = logging.getLogger(__name__)
class CorefDataProcessor:
def __init__(self, config, language='english'... |
'''Happy numbers'''
from itertools import islice
# main :: IO ()
def main():
'''Test'''
print((
take(8)(
happyNumbers()
)
))
# happyNumbers :: Gen [Int]
def happyNumbers():
'''Generator :: non-finite stream of happy numbers.'''
x = 1
while True:
x = until... |
import os
import sys
from datetime import datetime
def logger (come_from: str, text: str, output: str = None):
"""
Print log information
"""
# output is default => print ([DATETIME] from : text)
# output is file_path => file_handler = open (file_path, "a"); file_handler.write ([DATETIME] from : text\n);file_... |
"""
The table module includes a class :class:`~QuickBaseTable` that facilitates an ORM
to QuickBase API JSON through a meta class also defined in this module. There
is a dummy ~QuickBaseSchema object to allow easily getting
:class:`~QuickBaseField` data and not the value of the field.
"""
from typing import Dict
from... |
"""
Various general utilities used in the panel codebase.
"""
import ast
import base64
import datetime as dt
import inspect
import json
import numbers
import os
import re
import sys
import urllib.parse as urlparse
from collections.abc import MutableSequence, MutableMapping
from collections import defaultdict, OrderedD... |
# -*- coding: utf-8 -*-
""":Mod: wsgi
:Synopsis:
:Author:
ide
:Created:
7/12/21
"""
from webapp import app
if __name__ == '__main__':
app.run()
|
from sqlalchemy.sql import func
from project import db
class ImageTile(db.Model):
"""Describes the image tile database table and allows querying for image tile information"""
__tablename__ = 'tiles'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
z_coord = db.Column(db.Integer, nul... |
#!/usr/bin/env python2.5
#
# Copyright 2010 the Melange 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 applic... |
from dataclasses import asdict
import torch
from .interfaces import (
lassonet_path as _lassonet_path,
LassoNetClassifier,
LassoNetRegressor,
)
import numpy as np
def make_writable(x):
if isinstance(x, np.ndarray):
x = x.copy()
return x
def lassonet_path(X, y, task, *args, **kwargs):
... |
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QLabel, QFrame, QMenuBar, QMainWindow, QMenu
from PyQt5.QtCore import Qt, QRect, QSize, QPoint, QRectF
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QListWidget, QGridLayout, QSlider, QSpinBox, QRadioButton, QLineEdi... |
from marathon import MarathonClient, MarathonHttpError
from zappa.async import task
import os
import requests
import time
import yaml
dcos_username = os.environ['DCOS_USERNAME']
dcos_password = os.environ['DCOS_PASSWORD']
config = yaml.load(open('config.yaml'))
headers = {'Content-Type': 'application/json'}
payload ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import shutil
import tempfile
import unittest
import uuid
from contextlib import contextmanager
from typing import Generator, Optional
from unittest.mock import MagicMock, patch
from iopath.common import file_io
from iopath.common.file_... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 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 us... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
from cs231n.data_utils import *
from cs231n.classifiers.cnn import *
from cs231n.solver import Solver
# In[2]:
data = get_CIFAR10_data()
# In[3]:
[print(key, value.shape) for (key, value) in data.items()]
# In[4]:
cnn = ThreeLayerConvNet(reg=1e-3)
# In[5]:... |
#!/usr/bin/env python3
# Copyright 2019 Nina Marie Wahl and Charlotte Heggem.
# Copyright 2019 Norwegian University of Science and Technology.
#
# 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... |
import getopt
from lxml import etree
import os
import sys
import webbrowser
def help():
print("Please supply a scenario filename, e.g. FirstBullRun.xml, with a -f in front:")
print(' python battlecry.py -f <scenario_file> -d <display_file>')
print(' OR ')
print("Supply a scenario directory, e.g.... |
"""
Store Project on server.
"""
from modeldb.events.Event import *
class ProjectEvent(Event):
"""
Class for creating and storing ProjectEvents
"""
def __init__(self, project):
self.project = project
def make_event(self, syncer):
"""
Constructs a thrift ProjectEvent object ... |
"""
An interface for extending pandas with custom arrays.
.. warning::
This is an experimental API and subject to breaking changes
without warning.
"""
import operator
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union
import numpy as np
from pandas._libs import lib
from pandas._typing i... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import errno
from setuptools import setup, find_packages
from setuptools.command.install import install
from subprocess import check_ca... |
dia = int(input("Dia de nascimento: "))
mes = input("Número do mês de nascimento: ")
ano = input("Ano de nascimento: ")
print("Data formatada: {}/{}/{}".format(dia, mes, ano))
|
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
def string_with_arrows(text, pos_start, pos_end):
result = ''
idx_start = max(text.rfind('\n', 0, pos_start.idx), 0)
idx_end = text.find('\n', idx_start + 1)
if idx_end < 0: idx_end = len(text)
line_count = pos_end.ln - pos_start.ln + 1
for i in range(line_count):
line = text[idx_start:idx_end]
col_start =... |
from sympy.core import S, C, sympify, Function
from sympy.ntheory import sieve
from math import sqrt
class CombinatorialFunction(Function):
"""Base class for combinatorial functions. """
###############################################################################
######################## FACTORIAL and MULTI-FA... |
from pathlib import Path
import pytest
def pytest_addoption(parser):
parser.addoption(
"--root_dir",
type=Path,
)
parser.addoption(
"--target_annot",
type=str,
)
parser.addoption(
"--exception_path",
type=Path,
)
@pytest.fixture(scope="session"... |
from importbib import *
dest = "../_papers"
site = "unipi"
importBibliography(dest, site+".bib", site)
|
import django_filters
from django.contrib.auth.models import User
from django.db.models import Q
from .constants import *
from .models import ObjectChange, Tag
class ObjectChangeFilter(django_filters.FilterSet):
q = django_filters.CharFilter(method="search", label="Search")
time = django_filters.DateTimeFro... |
from django.contrib import admin
# Register your models here.
from chat.models import Room, Message
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
pass
@admin.register(Message)
class RoomAdmin(admin.ModelAdmin):
pass
|
"""
This file offers the methods to automatically retrieve the graph Rickettsia helvetica.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-0... |
from datetime import datetime, timedelta
from typing import Callable, List, Optional, Union
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlmodel ... |
from utilities.choices import ChoiceSet
#
# Sites
#
class SiteStatusChoices(ChoiceSet):
STATUS_ACTIVE = 'active'
STATUS_PLANNED = 'planned'
STATUS_RETIRED = 'retired'
CHOICES = (
(STATUS_ACTIVE, 'Active'),
(STATUS_PLANNED, 'Planned'),
(STATUS_RETIRED, 'Retired'),
)
... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import AccessToken, ScheduledAccess
class SlackTokenSerializer(serializers.ModelSerializer):
class Meta:
model = AccessToken
fields = ('client_id', 'app_id', 'integration', 'client_secret', 'signing... |
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SelectField, SubmitField
from wtforms.validators import Required
# class PitchForm(FlaskForm):
# category = SelectField('Category', choices=[('', ''), ('pickup lines', 'Pickup Lines'), ('technology', 'Technology Pitches'), ('product'... |
import filecmp
import os
import socket
import sys
import tempfile
import time
from unittest import mock
import docker
import pytest
import schema
from docker_cp import cli
def docker_responsive():
client = docker.from_env()
try:
return client.ping()
except Exception:
return False
def i... |
#!/usr/bin/env python3
#-*-coding:UTF-8-*-
from __future__ import print_function
import sys
import rospy
import cv2
import face_recognition
import numpy as np
from std_msgs.msg import Int32
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import glob
from... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2021 all rights reserved
#
# superclass
from ..algebraic.AbstractNode import AbstractNode
# declaration of the base node
class Datum(AbstractNode):
"""
The base class for nodes that have values
"""
# types
# augmented str... |
"""
Weighted ordered graphical model:
A graphical model (GraphModel) augmented with an elimination order and weights (inverse powers)
for that elimination, corresponding to an inference problem.
Always maintains factors is log form
Constructor: model or factors, order, temperature / weights.
Order construction: t... |
#101803562_Manpreet Kaur_COE26_Assignment6
import sys, os.path, copy, time, math
import pandas as pd
from os import path
import numpy as np
def check_source(source):
if not (path.exists(source)): # check file exists or not
print("No such file exists")
exit(0)
if not source.endswith... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 11:05:28 2021
@author: tomachache
"""
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
from qiskit.quantum_info.states.measures import state_fidelity
from qiskit.quantum_info import partial_trace
from QNN import QNN
from... |
from __future__ import print_function
import collections
import inspect
import logging
import sys
import time
import uuid
from pprint import pprint
import namegenerator
import pyfiglet
import terminal_banner
import urllib3
from six.moves.urllib.parse import urlparse
from termcolor import colored
import openapi_clien... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.