content stringlengths 5 1.05M |
|---|
class PGException(Exception):
""" A general exception for the proteoglycan pathway project """
pass
class OrthologRequestException(PGException):
""" An exception used for handling Ensembl API non-200 responses """
pass
class EmptyOrthologData(PGException):
""" An exception used for handling the ... |
import inspect
import numpy as np
from typing import Callable, Union
from .base import MlFlowBaseLogger
from .mlflow_func import log_params, log_metrics
class TrackMetric(MlFlowBaseLogger):
def __init__(
self,
function: Callable,
names: Union[list, str],
collect: Union[list, str, ... |
#!/usr/bin/python
import sys
def print_usage( argv ):
print "Creates mif file for font ROM."
print " Input: output file from nafe util"
print " Output: MIF file"
print "Usage: %s FONT_NAME_OUT_FILE_NAME MIF_FILE_NAME" % ( sys.argv[0] )
if __name__ == "__main__":
if len( sys.argv ) < 3:
print_usage... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
from twisted.enterprise import adbapi
from scrapy import signals
from scrapy.exporters i... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""WPT WebDriver tests runner."""
import pytest
import os
import argparse
import sys
import json
import tempfile
import time
import logging
_log = logging.... |
# Py.test
import pytest
pytestmark = pytest.mark.nondestructive
def test_auth_with_company_id_and_psk(public_api_v1):
result = public_api_v1.authentication()
assert result and result.get('success')
def test_auth_with_auth_file(public_api_v1_auth_file):
result = public_api_v1_auth_file.authentication()
... |
from __future__ import annotations
from component.component import Component
from logcat.logcat import LogCat
class Container(Component):
def __init__(self, x=0, y=0, width=1, height=1):
super().__init__(x, y, width, height)
self._components = []
@LogCat.log_func
def add(self, component... |
import random
import os
#d1 = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'.split()
deck = '3 K f A z D n W r m C Q A e X 5 m 9 S K 2 3 M J N x x k u s n B A o'.split()
#os.system ('clear')
random.shuffle(deck)
print (ra... |
from __future__ import annotations
from openhab_creator.models.configuration.location import Location, LocationType
@LocationType()
class Outdoor(Location):
@property
def area(self) -> str:
return 'Outdoor'
@property
def typed(self) -> str:
return 'Area'
class OutdoorType(Location... |
#!/usr/bin/env python3
from pathlib import Path
from typing import Any, Dict, Optional
import jinja2
from typing_extensions import Literal
DOCKER_REGISTRY = "308535385114.dkr.ecr.us-east-1.amazonaws.com"
GITHUB_DIR = Path(__file__).resolve().parent.parent
# it would be nice to statically specify that build_enviro... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
平衡二叉树python实现
avl树实现
"""
import math
import random
class Queue(object):
"""实现简易队列"""
def __init__(self):
self.data = []
self.head = 0
self.tail = 0
def is_empty(self):
return self.head == self.tail
... |
def Completo(S):
T=0
T = S.count(len(S)-1)
if (T == len(S)):
return("O grafo é completo, pois todos os vertices incidem sobre todos os outros\n")
else:
return("O grafo não é completo, pois todos os vertices não incidem sobre todos os outros\n")
|
"""Install GUI integration on Windows"""
import sys
import os
import argparse
# Check arguments
# command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--library", default="nbopen",
help="What Python library to open `.ipynb` with. E.g. 'nbopen' (for Jupyter Notebook) or '... |
from django.contrib import admin
from formularios.models import form_blog, contador
# Register your models here.
admin.site.register(form_blog)
admin.site.register(contador) |
# Code adapted from: https://towardsdatascience.com/build-it-yourself-chatbot-api-with-keras-tensorflow-model-f6d75ce957a5
# https://towardsdatascience.com/@andrejusb - Andrejus Baranovskis
import nltk
# nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
import numpy as... |
b = 10
c = 5
op = "%"
if op == "+":
res=b+c
elif op == "-":
res=b-c
elif op == "*":
res=b*c
elif op == "/":
res=b/c
else:
print("Operador invalido")
print(f"{b} {op} {c} = {res}")
|
# Generated by Django 3.2.5 on 2021-08-17 09:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('common', '0003_alter_city_options'),
]
operations = [
migrations.CreateModel(
name='Region',
... |
# Author: Xinshuo Weng
# email: xinshuo.weng@gmail.com
from PIL import Image
import numpy as np
import init_paths
from image_processing import image_crop_center
from xinshuo_visualization import visualize_image
from xinshuo_miscellaneous import CHECK_EQ_NUMPY
def test_crop_center():
image_path = '../lena.jpg'
img =... |
"""Test equals."""
from awesomeversion import AwesomeVersion
def test_equals():
"""Test equals."""
assert AwesomeVersion("2020.12.1") == AwesomeVersion("2020.12.1")
assert AwesomeVersion("2020") == AwesomeVersion("2020")
assert AwesomeVersion("2020") == AwesomeVersion("v2020")
assert AwesomeVersio... |
# coding: utf-8
import numpy as np
import re
import copy
import sys
#import networkx as nx
#import matplotlib.pyplot as plt
#import operator
#from collections import defaultdict
from collections import Counter
import time
def build_world(ii, DBG = True):
world = {}
xmin = ymin = 1000
xma... |
"""
Crie uma funcao que recebe como parametro um numero inteiro e devolve o seu dobro
"""
from random import randint
n1 = randint(0, 100)
def dobro(x):
print(x)
return x * 2
print(dobro(n1))
|
from Tkinter import *
tasklist = []
tasklist.append("Hey")
for task in tasklist:
print("Hello World!")
master = Tk()
master.mainloop() |
import string
# Open text file in reading mode
file = "Doc1.txt"
document = open(file, "r")
# initilise empty dictionary
dict = dict()
totalWordCount = 0
def removeWhitespaces(target):
start = 0
end = len(target)
for i in range(end):
if target[i] != " ":
start = i
break
... |
# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from siddhantbansal.preprocessing import ImageToArrayPreprocessor
from siddhantbansal.preprocessing import SimplePreprocessor
from siddh... |
import pandas as pd
import matplotlib
from matplotlib.ticker import (MultipleLocator)
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
df = pd.read_csv('scripts/plots/fig_3/DT_results.csv')
df_supervised = pd.read_csv('scripts/plots/fig_3/LfS_results.csv')
df['dataset'] = [x.replace('_', ' ').upper() for x in ... |
# -*- coding: utf-8 -*-
# standard library
# related
import pytest
# project
from ottd_ctrl.protocol import *
VALUE_RESULT = 'value_result'
RAW_DATA_RESULT = 'raw_data_result'
FIELD_RESULT = 'field_result'
DATA_RESULTS = 'data_results'
def _test_encode(value_result, type_class):
"""Generic encoding tests"""
... |
import torch.nn as nn
from utils.torch import *
class RNN(nn.Module):
def __init__(self, input_dim, out_dim, cell_type='lstm', bi_dir=False):
super().__init__()
self.input_dim = input_dim
self.out_dim = out_dim
self.cell_type = cell_type
self.bi_dir = bi_dir
self.mo... |
# -*- coding: utf-8 -*-
"""The common front-end functionality."""
class Frontend(object):
"""Class that implements a front-end."""
class TimeSlice(object):
"""Class that defines a time slice.
The time slice is used to provide a context of events around an event
of interest.
Attributes:
duration: dur... |
from __future__ import unicode_literals
import asyncio, discord
try:
from _command import Command
except:
from coms._command import Command
import functools
from concurrent.futures import ThreadPoolExecutor
from youtube_dl import YoutubeDL
import math
import os
import time
ydl_opts = {
'format': 'bes... |
"""Timezones lookup."""
import concurrent.futures
import time
import traceback
from datetime import datetime
from multiprocessing import cpu_count
from pathlib import Path
import albert as v0 # type: ignore
import pycountry
import pytz
import requests
import tzlocal
from fuzzywuzzy import process
__title__ = "Timez... |
from vpython import *
from math import *
import numpy as np
'''Datos del problema
Constante de gravitacion universal : G
Radio Cuerpo masa mayor : Cmayor
Masa mayor : M
Radio Cuerpo masa menor : Cmenor
Vector trayectoria : r
Vector trayecto... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
from functools import partial
from dautil.parser import cli_sort
__version__ = "0.1"
def main(args):
for line in args.infile:
print((cli_sort(line, args.n)), file=args.output)
def cli():
parser = arg... |
"""
Define the export_course_metadata Django App.
"""
from django.apps import AppConfig
class ExportCourseMetadataConfig(AppConfig):
"""
App for exporting a subset of course metadata
"""
name = 'cms.djangoapps.export_course_metadata'
def ready(self):
"""
Connect signal handler th... |
# Bundles all the code in /src directory |
#
# Weekday Count Challenge
# Write a program that counts the number of a certain weekday in the month and year that the user enters
#
import calendar
# This function counts the number of the given weekday for the specified year and month and returns the result
def countdays(theyear, themonth, whichday):
daycount... |
# 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 List, Optional
from beanmachine.ppl.legacy.inference.abstract_mh_infer import AbstractMHInference
from beanmachine.ppl.l... |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""
"""
import ast
import datetime
import os
import sys
import time
from typing import Optional
import csv
import requests
from crowdin_api import CrowdinClient
class FirstCrowdinClient(CrowdinClient):
TOKEN = ... |
@njit
def create_n_random_particles(n, m, domain=1):
'''
Creates `n` particles with mass `m` with random coordinates
between 0 and `domain`
'''
parts = numpy.zeros((n), dtype=particle_dtype)
#attribute access only in @jitted function
for p in parts:
p.x = numpy.random.random() * doma... |
from flask import Flask, render_template, request, redirect
from os.path import abspath, dirname
import platform
import sys
from os import path
import json
import os
#messy stuff from importing from ../
basepath = path.dirname(__file__)
filepath = path.abspath(path.join(basepath, "../../", "habit-at"))
sys.... |
# automatically generated, do not modify
# namespace: fbs
import flatbuffers
class KalmanGainMatrix(object):
__slots__ = ['_tab']
# KalmanGainMatrix
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# KalmanGainMatrix
def K00(self): return self._tab.Get(flatbuffers... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""hb_render.py
hb_render.HarfBuzzRenderer class
wraps the 'hb-view' and 'hb-shape' Harfbuzz utilities
* https://github.com/behdad/harfbuzz
using the Python 'sh' module
* https://amoffat.github.io/sh/
* https://pypi.python.org/pypi/sh
"""
import json
import os.path
imp... |
import numpy as np
import torch
import torch.utils.data
from transformer import Constants
class EventData(torch.utils.data.Dataset):
""" Event stream dataset. """
def __init__(self, data):
"""
Data should be a list of event streams; each event stream is a list of dictionaries;
each d... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, backend, models, utils
from .utils import deduce_input_shape
def conv2d(input,
filters,
rows,
columns,
padding='same',
strides=(1,1),
name='conv',
data_format='channels_last',
... |
from floodsystem.stationdata import build_station_list
from floodsystem.station import inconsistent_typical_range_stations
from floodsystem.station import MonitoringStation
def run():
"""Requirements for Task 1F"""
# List of Stations
stations = build_station_list()
incon = inconsistent_typical_range_s... |
from skimage.metrics import structural_similarity
import numpy as np
def ssim_metric(org_img: np.ndarray, pred_img: np.ndarray) -> float:
"""
Structural SIMularity index
"""
#_assert_image_shapes_equal(org_img, pred_img, "SSIM")
if len(org_img.shape) >2:
multichannel = True
else:
multichannel = False
org_i... |
import numpy
import struct
import binascii
# sensors for the controllers
class Sensors():
def get(self, game):
# calculates vertical and horizontal distances between sprites centers
posx_p = game.player.rect.left +((game.player.rect.right - game.player.rect.left)/2)
posy_p = game.playe... |
from redis import Redis
from choreo.multirq import Queue
import time
import threading
import random
def main():
queue = Queue(connection=Redis())
result = queue.enqueue('tasks.sleepy', args=(random.randint(20, 20),), timeout=10)
tic = time.time()
while result.get_status() not in ('finished', 'failed'... |
from mangum import Mangum
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .routers.api import api
from .settings import settings
app = FastAPI(
title=settings.APP_SETTINGS.PROJECT_NAME,
description=settings.APP_SETTINGS.PROJECT_DESCRIPTION,
version=settings.APP_SETTING... |
from __future__ import absolute_import
import pytz
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from sentry.incidents.models import AlertRule, IncidentTrigger
from sentry.models.project import Project
from datetime import datetime
@receiver(post_save, sender=Projec... |
import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories."
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday"
),
(
... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility and helper functions for 'twisted' library use and integration."""
import httplib
import urlparse
import twisted.web.client
import twisted.web.e... |
import unittest
import processTimeTrackingEntries
import os
import logging
class JiraTest(unittest.TestCase):
configuration = {}
_logger = logging.getLogger(__name__)
def setUp(self):
self.configuration = processTimeTrackingEntries.read_configuration(
os.path.join(os.path.abspath(os.... |
import math
import torch
import torch.nn.functional as F
from numpy import prod
from torch.nn import init
from .matrix import tt_to_matrix
class TTLinear(torch.nn.Module):
"""Tensor-Train linear layer, proposed in [1]_.
References
----------
.. [1] Novikov, A., Podoprikhin, D., Osokin, A., & Vetro... |
# coding: utf-8
# In[1]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np
import matplotlib.pyplot as plt
# Add Bayesian-and-novelty directory to the PYTHONPATH
import sys
import os
sys.path.append(os.pat... |
import logging
import torch.nn as nn
from ...weight_init import init_weights
from ..builder import build_brick, build_bricks
from ..registry import DECODERS
logger = logging.getLogger()
@DECODERS.register_module
class GFPN(nn.Module):
"""GFPN
A general framework for FPN-alike structures.
"""
def __... |
from cpt.packager import ConanMultiPackager
if __name__ == "__main__":
builder = ConanMultiPackager(username="kth", channel="stable", archs=["x86_64"]
, remotes="https://knuth.jfrog.io/artifactory/api/conan/knuth")
builder.add_common_builds(shared_option_name="lmdb:shared", pure... |
#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
# Copyright 2013-2014 Sebastian Werner
#
import re
import copy
import polib
import jasy.script.parse.Node as Node
import jasy.item.Translation as Translation
from jasy import UserError
import jasy.core.Console as Console
#
# Public API
#
__all__ = ... |
import os.path
import os
def get_key():
key_path = os.path.expanduser("~/.steamapi")
if os.path.exists(key_path):
with open(key_path, 'r') as f:
key = f.read().strip()
else:
key = os.environ['STEAMAPI']
# try:
# key = raw_input("Enter Steam API key: ")
... |
"""
Salt execution module for VMC vm stats
Provides methods to get cpu or memory related settings of a virtual machine
"""
import logging
from saltext.vmware.utils import vmc_constants
from saltext.vmware.utils import vmc_request
from saltext.vmware.utils import vmc_vcenter_request
log = logging.getLogger(__name__)
... |
# -*- coding: utf-8 -*-
"""
(c) 2016 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
from __future__ import unicode_literals, absolute_import
import sqlalchemy as sa
import wtforms
try:
from flask_wtf import FlaskForm
except ImportError:
from flask_wtf import Form as Fla... |
from urllib.parse import urlparse
from collections import defaultdict
def extract(x):
domain = urlparse(x.href).netloc
return domain
infinite_defaultdict = lambda: defaultdict(infinite_defaultdict)
def recurse_print_infinitedict(d, prefix=''):
if type(d) != defaultdict:
print(prefix, d)
re... |
# -*- coding:utf8 -*-
# !/usr/bin/env python
# Copyright 2019 Google Inc. 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... |
from __future__ import annotations
import pytest
from refill.filters import Filters, default_filters
def test_copy():
filters = default_filters.copy()
filters.register("test", lambda x: x.upper())
assert filters.apply("testing", "test", []) == "TESTING"
with pytest.raises(KeyError):
default_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-03-17 23:41
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
#!/usr/bin/env python
# coding=utf-8
# __author__='walker'
"""
捕获类似curses键盘输入流,生成指令流
"""
import curses
from copy import deepcopy
from functools import wraps
from .config import Config
ERASE_SPEED = 5 # 屏幕5秒刷新一次 去除错误的显示
__all__ = ["cmd_parser", "parse_keylist", "coroutine", "erase_coroutine"]
KEY_MAP = Config().get... |
from functools import wraps
from flask import jsonify
from flask import g
from flask import Response
from flask import current_app
from flask_openid import OpenID
from gleague import core
from gleague import admin
oid = OpenID()
def create_app(name=__name__):
app = core.create_app(name)
for e in [401, 403,... |
# Welcome user
import unicodedata
import re
# A introduction paragraph for user to read and understand what is autoimmune diseases.
def print_intro():
intro = input("Do you want to read some introduction? (y/n) ").lower()
if intro == 'y':
print("\nAn autoimmune disease is a condition in which your immu... |
from distutils.core import setup
setup(
name='hub_dados',
version='1.1.0',
packages=['hub_dados'],
url='https://github.com/amisampaio/hub_dados',
license='Apache 2.0',
author='Amilcar Sampaio',
author_email='amilcar.sampaio@gmail.com',
description='Hub de dados'
)
|
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port, Stop, Direction, Button
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
import time
left = Motor(Port.B)
right = ... |
import GPUtil
import keras
import keras.backend as K
import numpy as xp
import os
def get_n_fft(magnitude):
return magnitude.shape[-1] * 2 - 2
def get_stft(n_fft):
n_hop = n_fft // 4
window = xp.hanning(n_fft)
spec_width = n_fft // 2 + 1
def stft(signal):
length = 1 + (signal.shape[0] - n_... |
from functools import singledispatch
from sklearn.base import RegressorMixin, ClassifierMixin
from .utils import MeanEstimator, MeanClassifier, MeanRegressor
@singledispatch
def _fallback_dispatch(piecewise):
model = MeanEstimator()
return model
@_fallback_dispatch.register(RegressorMixin)
def _fallback_dispa... |
weight=3
def run():
_print('2')
sleep(4)
_task_suspend('t1')
_print('shouldnt gethere')
|
from flask import Flask,jsonify
from json import load
from flask_cors import CORS
with open('valid_aids_file.json', 'r') as aids_file:
valid_aids = load(aids_file)
with open('valid_parties.json', 'r') as parties_file:
valid_parties= load(parties_file)
app = Flask(__name__)
CORS(app)
@app.route('/aids/<int:ai... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
import mysql.connector
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mydb = mysql.connector.connect(host = "host", user = "usr", passwd = "pwd", database = "db")
mycursor = mydb.cursor()
mycursor2 = mydb.cursor()
sql_q... |
import random
import time
import platform
import subprocess
from time import sleep
def clear_screen():
"""
Clears the terminal screen.
"""
# Clear command as function of OS
command = "cls" if platform.system().lower()=="windows" else "clear"
# Action
return subprocess.call(command) == 0
... |
def test_exec_bpftrace():
lines = ['@[2295, etcd]: 1', '@[289, multipathd]: 1', '@[2240, kube-controller]: 1', '@[3403, STREAM_RECEIVER]: 1',
'@[708, kubelet]: 3', '@[707, dockerd]: 4', '@[2303, kube-apiserver]: 7', '@[0, swapper/1]: 287',
'@[0, swapper/0]: 288']
|
from struct import Struct
def read_records(format, f):
record_struct = Struct(format)
chunks = iter(lambda: f.read(record_struct.size), b'')
return (record_struct.unpack(chunk) for chunk in chunks)
# Example
if __name__ == '__main__':
with open('data.b','rb') as f:
for rec in read_records('<id... |
#!/usr/bin/python3
import boto3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
# upload a new file
data = open(r'c:\work\test_images\test_images_small\t_0003.png', 'rb')
s3.Bucket('z0001-bucket').put_object(Key='t_0003.png', Body=data)
|
import nltk,re,codecs
from nltk.tokenize import word_tokenize,sent_tokenize
from backNode import BackNode
from nltk import Tree
def trace_tree(trace):
if trace.left==None and trace.right==None:
return str(trace.root)+" "+str(trace.word)
return "("+str(trace.root)+"("+str(trace_tree(trace.left))+")"+" "+"("+str... |
import bottle
bottle.TEMPLATE_PATH = ['template']
from bottle import Bottle, run, template
app = Bottle()
@app.route('/')
@app.route('/<name:re:[a-z]+>')
def index(name='world'):
return template('script-01', name=name)
run(app, host='localhost', port=8080) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-31 16:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('huddle_board', '0011_card_tags'),
]
operations = [
migrations.AddField(
... |
#for market table and a lookup table returns a csv with only US aggregated markets
import csv
def main():
lookup_path = "lookup_market.asp"
table_path = "313048317_T_DB1B_MARKET.csv"
in_table = set()
table = open(table_path, 'r')
lookup = open(lookup_path, 'r')
table_rows = csv.reader(table, quoting=csv.QUOTE_NO... |
# Vim YouCompleteMe completion configuration.
#
# See doc/topics/ycm.md for details.
import os
import platform
repo_root = os.path.dirname(os.path.abspath(__file__))
# Paths in the compilation flags must be absolute to allow ycm to find them from
# any working directory.
def AbsolutePath(path):
return os.path.join... |
__author__ = 'manuelli'
import contactfilter
import contactfiltervisualizer
from contactfilterutils import EstRobotStatePublisher
import externalforce
import linkselection
import cpftester
import argparse
import director.applogic as app
import os
def startup(robotSystem, globalsDict=None):
""""
Creates clas... |
# ------------------------------------------------------------------------------
# Utility functions.
# Written by Bowen Cheng (bcheng9@illinois.edu)
# ------------------------------------------------------------------------------
class AverageMeter(object):
"""Computes and stores the average and current value"""... |
import numpy as np
class NeuralNets:
def __init__(self,inputs,hidden,outputs,lr=0.3):
self.bias_ih = np.random.randn(hidden,1)
self.bias_ho = np.random.randn(outputs,1)
self.weights_ih = np.random.randn(hidden,inputs)
self.weights_ho = np.random.randn(outputs,hidden)
self.... |
import math
def angle(pt0, pt1, pt2):
dx1 = float(pt0[0] - pt1[0])
dy1 = float(pt0[1] - pt1[1])
dx2 = float(pt2[0] - pt1[0])
dy2 = float(pt2[1] - pt1[1])
return (dx1 * dx2 + dy1 * dy2) / math.sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10)
def max_cosine_from_contour(contour):
... |
#!/usr/bin/python3
import numpy as np
from itertools import product
from learning.model_based import Problem
from learning.model_based import policy_iteration
from learning.model_based import value_iteration
class GridProblem(Problem):
def __init__(self, side=4, final=0):
self.side = side
self.s... |
#!/usr/bin/python
#
# Find a sequence of duk_hobject hash sizes which have a desired 'ratio'
# and are primes. Prime hash sizes ensure that all probe sequence values
# (less than hash size) are relatively prime to hash size, i.e. cover the
# entire hash. Prime data is packed into about 1 byte/prime using a
# pre... |
# -*- coding: utf-8 -*-
from pyee._base import BaseEventEmitter
try:
from concurrent.futures import ThreadPoolExecutor
except ImportError:
from futures import ThreadPoolExecutor
__all__ = ['ExecutorEventEmitter']
class ExecutorEventEmitter(BaseEventEmitter):
"""An event emitter class which runs handler... |
import json
import logging
import os
from urllib.parse import urlparse
from django.conf import settings
logger = logging.getLogger(__name__)
def move_tus_upload(upload_url, move_function):
"""
Move upload identified by upload_url using the provided move_function.
move_function signature should be (file... |
from dash import html, dcc, dash_table
from dashboard.styles import layout, infographic, base, colors
from plotly import graph_objects as go, colors as c
from typing import List
def info(data: any):
children = data if isinstance(data, list) else [data]
return html.Div(children, className="text-info")
def va... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 12:30:17 2018
@author: yume
パターン認識と機械学習 下
p.154-155参照
"""
import numpy as np
import matplotlib.pyplot as plt
import mixture_distributions
def gaussian_pdf(x, mean, var):
return np.exp(-(x-mean)**2/(2*var)) / (2*np.pi*var)**0.5
def gamma(x, mean, var, pi):
... |
#
# 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... |
import django_filters as filters
from . import models
class IndividuFilter(filters.FilterSet):
nom = filters.CharFilter(lookup_expr="icontains")
epouse = filters.CharFilter(lookup_expr="icontains")
prenom = filters.CharFilter(lookup_expr="icontains")
usage = filters.CharFilter(lookup_expr="icontains"... |
from __future__ import print_function, division, absolute_import
from collections import namedtuple
import contextlib
import pickle
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant, LLVMException
import llvmlite.llvmpy.core as lc
from numba.config import PYVERSION
import numba.ctypes_support a... |
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
#
# Overlay To Underlay Mapper
#
# Utility to get the Underlay information for the Overlay flow(s).
#
import json
from sandesh.viz.constants import *
from opserver_util import OpServerUtils
class OverlayToUnderlayMapperError(Exception):
"""Ba... |
# Generated by Django 3.0.7 on 2020-12-23 07:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foodcartapp', '0055_auto_20201222_2125'),
]
operations = [
migrations.AddField(
model_name='customerorder',
name='pa... |
# coding=utf-8
# Copyright (C) 2021+ Alice, Vigo, Spain
"""Public API of Alice Petisco Framework"""
from petisco.base.application.application import Application
from petisco.base.application.application_configurer import ApplicationConfigurer
from petisco.base.application.controller.controller import Controller
from p... |
#! /usr/bin/python3
"""
helper functions for use in various scripts
"""
import os.path
def get_absolute_path_before_moving_to_directory(root_directory : str,
destination_directory : str,
file_or_folder_to_move : str,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.