content stringlengths 5 1.05M |
|---|
from GTDLambda import *
from TileCoder import *
import numpy
class DirectStepsToLeftDemon(GTDLambda):
def __init__(self, featureVectorLength, alpha):
GTDLambda.__init__(self, featureVectorLength, alpha)
def gamma(self, state, observation):
encoder = observation['encoder']
if (encoder ... |
import os
import numpy as np
from tqdm import tqdm
from PIL import Image
from imagededup.methods import PHash
def run(root: str):
phasher = PHash()
img = Image.open("/home/huakun/datasets/meinv/anime/IMG_0903.PNG")
size = np.asarray(img.size)
scale = 0.1
new_size = (size * scale).astype(int)
i... |
#!python
"""
Keras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.
The current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.
Adopting to other backends should be easy, but I have not tested this.
Usage:
python capsulen... |
# Copyright 2016 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... |
import configparser
import collections
import os
import json
import copy
from .utils import parse_timedelta
from .scrape import get_all_scrapers
import argparse
# Configuration handling
class AltJobOptions(collections.UserDict):
"""
Wrap argparse and configparser objects into one configuration dict object
... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from multi_var_gradient_decent import LinearRegressionUsingGD
from mpl_toolkits.mplot3d import axes3d
from sklearn.metrics import mean_squared_error, r2_score
def create_mesh_grid(start, end):
theta_1 = np.linspace(start, end, 30)
th... |
import mxnet as mx
import utils
from model_utils import validate_model
from gluon_zoo import save_mobilenet1_0
from from_tensorflow import tf_dump_model
from os import path
def test_tf_resnet50_v1():
sym_path = "./data/tf_resnet50_v1.json"
prm_path = "./data/tf_resnet50_v1.params"
# if not path.exists(sy... |
import click
import reader
from reader._cli import setup_logging
def make_add_response_headers_middleware(wsgi_app, headers):
def wsgi_app_wrapper(environ, start_response):
def start_response_wrapper(status, response_headers, exc_info=None):
response_headers.extend(headers)
return... |
from collections import defaultdict
"""
Block
"""
class Block:
def __init__(self, author, round, payload, qc, id, txn_id):
self.author = author
self.round = round
self.payload = payload
self.qc = qc
self.id = id
self.txn_id = txn_id
self.children = []
... |
try:
from webdriver_manager.chrome import ChromeDriverManager
except: raise ImportError("'webdriver-manager' package not installed")
try:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
except: raise ImportError("'selenium' package not installed")
from bs4 import BeautifulSoup... |
import requests
user = 'alexey'
password = 'styagaylo'
base_url = 'http://httpbin.org/'
def test_my_first_api():
r = requests.post(base_url + 'post', data={'user': user, 'password': password})
assert r.status_code == 200, "Unexpected status code: {}".format(r.status_code)
assert r.json()['url'] == base_ur... |
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from matplotlib import pylab
import matplotlib.pyplot as plt
import networkx as nx
# read results from the file
docs = eval(open('final_out_dupe_detect.txt', 'r').read())
final_docs = [[i[0], list(set(... |
import re
import os
import math
import subprocess
from MadGraphControl.MadGraphUtils import *
nevents = 10000
mode = 0
mass=0.500000e+03
channel="mumu"
gsmuL=-1
gseL=-1
gbmuL=-1
gbeL=-1
JOname = runArgs.jobConfig[0]
matches = re.search("M([0-9]+).*\.py", JOname)
if matches is None:
raise RuntimeError("Cannot fi... |
# coding: utf-8
import sys
import utils
# python .github/workflows/scripts/override_version.py example/tools/analyzer_plugin/pubspec.yaml 1.1.0
pubspec_yaml = sys.argv[1]
version = sys.argv[2]
utils.override_version(pubspec_yaml, version) |
"""Define a version number for turboPy"""
VERSION = ('2020', '10', '14')
__version__ = '.'.join(map(str, VERSION))
|
from django.db import models
# Create your models here.
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(_(""), auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(_(""), auto_now=True, auto_now_add=False)
class Meta:
abstract = True
class Image(TimeStampe... |
#
# Copyright 2018 Jaroslav Chmurny
#
#
# This file is part of Python Sudoku Sandbox.
#
# Python Sudoku Sandbox is free software developed for educational and
# experimental purposes. It is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# Licens... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2022 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import abc
import json
import logging
from typing import Optional, List, Set, Tuple
from google.protobu... |
"""
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] =>... |
from __future__ import annotations
import os
import warnings
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
Union,
Sequence,
Iterable,
)
import pydantic
from .managers import ManagerQueryBody, ComputeManager
from .metadata... |
import sys
import jinja2
import tdclient
import tdclient.version
from .version import __version__
import logging
logger = logging.getLogger(__name__)
class Context(object):
'''High-level wrapper for tdclient.Client.'''
def __init__(self, module=None, config=None):
if config is None:
conf... |
import agama
mass_unit = (1.0/4.3)*(10.0**(6.0))
agama.setUnits(mass=mass_unit, length=1, velocity=1)
pot = agama.Potential(type='Spheroid', gamma=1.0, beta=3.1, scaleRadius=2.5, outerCutoffRadius=15.0)
df = agama.DistributionFunction(type='QuasiSpherical',potential=pot)
model = agama.GalaxyModel(pot,df)
M = model.s... |
# Developed for the LSST System Integration, Test and Commissioning Team.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause ... |
# Import the toolkit specific version.
from pyface.toolkit import toolkit_object
TaskWindowBackend = toolkit_object(
'tasks.task_window_backend:TaskWindowBackend')
|
# Based on
# https://www.paraview.org/Wiki/Python_Programmable_Filter#Generating_Data_.28Programmable_Source.29
#This script generates a helix curve.
#This is intended as the script of a 'Programmable Source'
def _helix(self, numPts):
import math
#numPts = 80 # Points along Helix
length = 8.0 # Length of Hel... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from Propylaea.forms import LoginForm, SignUpForm
from django.template import loader
from django.contrib.auth.decorators import login_required
de... |
#!/usr/bin/env python
import numpy as np
import h5py as h
import matplotlib
import matplotlib.pyplot as plt
import sys, os, re, shutil, subprocess, time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", action="store", type="string", dest="inputFile", help="Input H5 file with... |
import numpy as np
import math
# from mxnet import nd
from mxnet.gluon import nn
class Augmentation(nn.HybridBlock):
def __init__(self, angle_range, zoom_range, translation_range, target_shape, orig_shape, batch_size,
aspect_range = None, relative_angle = 0, relative_scale = (1, 1), relative_translation = 0):
sup... |
from __future__ import absolute_import
import os
import sys
import pytest
from collections import defaultdict
myPath = os.path.abspath(os.getcwd())
sys.path.insert(0, myPath)
from salt.exceptions import ArgumentValueError
import hubblestack.extmods.fdg.process
class TestProcess():
"""
Class used to test th... |
from pprint import pprint
def sort_with_index(arr):
arr_with_index = []
for i, item in enumerate(arr):
arr_with_index.append((i, item))
arr_with_index.sort(key=lambda it: -it[1])
return arr_with_index
def assign(jobs_with_index, n_not_fulfilled_jobs, n_machines):
assignment = {}
assi... |
'''
Copyright 2022 Airbus SAS
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 writing, sof... |
#!python
"""
ANNOTATE FUNCTIONS WITH TIME AND SPACE COMPLEXITY!!!!!
"""
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(ar... |
import json
import sys
import os
from time import sleep
import wxpy
class Greeting:
def __init__(self, name, puid, greeting='{name}新年快乐!狗年大吉!'):
self.name = name
self.puid = puid
self._greeting = greeting
def toJSON(self):
# return str(self.__dict__)
return json.d... |
# ----------------------------------------------------------------------
# |
# | CentOsShell.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2019-08-30 19:25:23
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2019-22.
# | Distributed ... |
class ReasonCode:
"""Default server reason codes."""
# General error
GENERAL_ERROR = 1
# General session error
SESSION_ERROR = 11
# The session resource is already registered
SESSION_REGISTRATION_ERROR = 12
# An authentication error occurred
SESSION_AUTHENTICATION_FAILED = 13
# ... |
from django.db import models
from subscribers import mailchimp
class AbstractSubscriber(models.Model):
email = models.EmailField(blank=True, null=True)
created_on = models.DateField(auto_now_add=True)
objects = models.Manager()
class Meta:
abstract = True
def __str__(self):
retur... |
from possum import *
spec = possum()
spec._generateParams(N=30000, fluxMin=0.1, noiseMax=0.2, pcomplex=0.5, seed=923743)
spec._simulateNspec(save=True, dir='data/train/V2/', timeit=True)
|
from django.db import models
from djangae.tasks.deferred import defer
from djangae.test import TestCase, TaskFailedError
def test_task(*args, **kwargs):
pass
def assert_cache_wiped(instance):
field = DeferModelA._meta.get_field("b")
assert(field.get_cached_value(instance, None) is None)
class DeferMod... |
# 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 required by applicable law or a... |
"""
MSX SDK
MSX SDK client. # noqa: E501
The version of the OpenAPI document: 1.0.9
Generated by: https://openapi-generator.tech
"""
import unittest
import python_msx_sdk
from python_msx_sdk.api.workflow_events_api import WorkflowEventsApi # noqa: E501
class TestWorkflowEventsApi(unittest.TestC... |
# coding: utf-8
__author__ = 'Paul Cunningham'
__email__ = 'pjcunningham@borsuk.co.uk'
__copyright = 'Copyright 2017, Paul Cunningham'
__license__ = 'MIT License'
__version__ = '0.1'
from .select2 import Select2
|
import numpy as np
import pandas as pd
returns = prices.pct_change()
returns.dropna()
returns.std()
deviations = (returns - returns.mean())**2
squared_deviations = deviations ** 2
variance = squared_deviations.mean()
volatility = np.sqrt(variance)
me_m = pd.read_csv('./Data/Portfolios_Formed_on_ME_monthly_EW.csv',... |
import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class AccountUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory("AccountUD")
|
from turtle import color
import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np
import math
th = np.linspace(0, 2*np.pi, 1000)
r=1
c=r*np.cos(th)
d=r*np.sin(th)
figure, axes = plt.subplots(1)
axes.plot(c,d)
axes.set_aspect(1)
plt.title("sensor position")
plt.plot(1,0,'o',color="blue",)
plt... |
#!/usr/bin/python3
import itertools
import os
import re
_RE_INCLUDE = re.compile('#include ([<"])([^"<>]+)')
_LIB_BY_HEADER = {
'curl/curl.h': 'curl',
're2/re2.h': 're2',
'sqlite3.h': 'sqlite3',
}
def dfs(root, get_children):
todo = [root]
visited = {id(root)}
while todo:
item = todo.pop()
yiel... |
from django.contrib import admin
from django.urls import path
from .views import IndexClassView, index
urlpatterns = [
path("", index, name="home"),
path(
"class", IndexClassView.as_view(template_name="index.html"), name="home_class"
),
path(
"class2",
IndexClassView.as_view(te... |
# -*- coding:utf-8 -*-
from __future__ import print_function
import math
import numpy as np
import os
import sys
sys.path.insert(0, '../facealign')
sys.path.insert(0, '../util')
from caffe_extractor import CaffeExtractor
def model_centerface(do_mirror):
model_dir = './models/centerface/'
model_proto = mod... |
from raytracer.tuple import (
tuple,
point,
vector,
magnitude,
normalize,
dot,
cross,
reflect,
Color,
)
from raytracer.rays import Ray
from raytracer.spheres import Sphere
from raytracer.intersections import Intersection, intersections, hit, prepare_computations
from raytracer.lights... |
import os
import pathlib
import urllib
import bs4
from .subsearcher import HTMLSubSearcher, SubInfo
class SubHDSubSearcher(HTMLSubSearcher):
"""SubHD 字幕搜索器(https://subhd.tv)"""
SUPPORT_LANGUAGES = ['zh_chs', 'zh_cht', 'en', 'zh_en']
SUPPORT_EXTS = ['ass', 'srt']
API_URL = 'https://subhd.tv/search/'
... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import pickle
class MyContainer(object):
def __init__(self, data):
self._data = data
def get_data(self):
return self._data
d1 = MyContainer([2, 5, 4, 3, [ 12, 3, 5 ], 32, { 'a': 12, 'b': 43}])
with open('/tmp/pickle_data.dat', "wb") as f:
... |
import os
import urllib
import elasticsearch
import elasticsearch_dsl
import es2json.helperscripts as helperscripts
class ESGenerator:
"""
Main generator Object where other Generators inherit from
"""
def __init__(self, host='localhost',
port=9200,
es=None,
... |
from copy import deepcopy
from sqlalchemy import (
Table,
Column,
Integer,
String,
DateTime,
UniqueConstraint,
DECIMAL,
LargeBinary,
Boolean,
ForeignKey,
PrimaryKeyConstraint,
)
from wt.common import Currency
from wt.entities.deliverables import DeliverableStatus
from wt.id... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 ckitagawa <ckitagawa@edu.uwaterloo.ca>
#
# Distributed under terms of the MIT license.
import logging
import threading
import serial
import serial.tools.list_ports
import fiber_reading
from collections import deque
def select_devic... |
# 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 use ... |
# -*- coding: utf-8 -*-
from typing import Dict, List, Optional, Tuple
from django.conf import settings
from rest_framework import serializers
from backend.components import bk_repo
from backend.helm.helm.models.chart import Chart, ChartVersion, ChartVersionSnapshot
def get_chart_version(
project_name: str, rep... |
import os
from collections import OrderedDict
from coverage_checker.utils import get_all_path_combinations
def test_get_all_path_combinations():
facets = OrderedDict([('a', ['1', '2']), ('b', ['3', '4']), ('c', ['5', '6'])])
all_paths = get_all_path_combinations(facets)
expected_result = ['1/3/5', '... |
import re
from math import sqrt, atan2
if __name__ == "__main__":
"""
This script file demonstrates how to transform raw CSI out from the ESP32 into CSI-amplitude and CSI-phase.
"""
FILE_NAME = "./example_csi.csv"
f = open(FILE_NAME)
for j, l in enumerate(f.readlines()):
imaginary = ... |
# Recording video to a file
# https://picamera.readthedocs.io/en/release-1.13/recipes1.html#recording-video-to-a-file
import picamera
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_recording('output/07_video.h264')
camera.wait_recording(5)
camera.stop_recording() |
# Copyright 2015 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.0
#
# Unless required by applicable law or ... |
# -----------------------------------------------------------------------------
# Copyright (c) 2013-2022, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -------------------------------------------------... |
import os
import sys
from PIL import Image
import glob
import numpy as np
import h5py
import csv
import time
import zipfile
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
def reporth... |
import sys
# Expose the public API.
from ehrpreper.api import *
# Check major python version
if sys.version_info[0] < 3:
raise Exception("Ehrpreper does not support Python 2. Please upgrade to Python 3.")
# Check minor python version
elif sys.version_info[1] < 6:
raise Exception(
"Ehrpreper only suppo... |
__author__ ='Jacques Saraydaryan'
class ColorRange():
min_H=0
max_H=0
label=''
def getColor(self,minH,maxH,label):
self.min_H=minH
self.max_H=maxH
self.label=label
|
#! /usr/bin/env python
import rospy, std_msgs.msg
from sensor_msgs.msg import Temperature
pub = rospy.Publisher('henri/temp_average', Temperature, queue_size=10)
average = 0
variance = 0
def callback(data):
global average, variance, pub
rospy.loginfo('Temperature Received: %f', data.temperature)
average =... |
from flask import Flask
from config import config_options
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import UploadSet,configure_uploads,IMAGES
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_simplemde import SimpleMDE
from flask_mail ... |
# import numpy as np
# import matplotlib.pyplot as plt
# import cv2
# img = cv2.imread('8.jpeg',0)
# dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
# dft_shift = np.fft.fftshift(dft)
# magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
# plt.subplot(121),plt.imshow... |
from flask import json, render_template, g, abort
from flask_login import current_user, login_required
import urllib, json
from thanados import app
from thanados.models.entity import Data
@app.route('/vocabulary/')
def vocabulary():
hierarchytypes = app.config["HIERARCHY_TYPES"]
systemtypes = app.config["SY... |
# TensorFlow and tf.keras
import tensorflow as tf
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
# Display the image, labeled with the predicted label (blue if accurate to true label, red if not)
def plot_image(i, predictions_array, true_label, img):
true_label, img = true_label[i], img[i]
... |
import os
import os.path as osp
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
from torchvision.transforms import functional as F
import numpy as np
import numpy.linalg as LA
import cv2
import json
import csv
import matplotlib.pyplot as plt
from pylsd import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: mcxiaoke
# @Date: 2015-07-10 14:13:05
import os
import sys
from os import path
import re
import tempfile
import shutil
import time
'''
clean idea project files
param: max_depth -> max depth for recursively, default=3
param: permanently -> move to ... |
import os
from .handler import QuickOpenHandler
from ._version import get_versions
from notebook.utils import url_path_join
__version__ = get_versions()['version']
del get_versions
def _jupyter_server_extension_paths():
"""Defines the entrypoint for the Jupyter server extension."""
return [{
"modul... |
from abc import ABC
from typing import Type
from bokeh.models.glyph import Glyph
from bokeh.models.renderers import GlyphRenderer
from xbokeh.common.assertions import assert_type
class Renderer(ABC):
def __init__(self, type_: Type, renderer: GlyphRenderer) -> None:
"""
:renderer: instance of Gly... |
from math import log
from utils import iter_primes
__author__ = 'rafa'
def algorithm(limit):
n = 1
for p in iter_primes():
if p > limit:
return n
exponent = int(log(limit, p))
n *= p**exponent
def solver():
"""
2520 is the smallest number that can be divided by e... |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def plot_time_series(x: np.ndarray, title=None) -> None:
sns.set(font_scale=1.5)
sns.set_style("white")
t = np.arange(start=0, stop=x.shape[0])
plt.plot(t, x, linestyle='-', marker='o')
plt.title(title)
plt.xlabel(r'$t$')... |
from __future__ import print_function
import argparse
import os
import sys
import time
import random
import string
from typing import getch
import torch
import torch.nn as nn
from torch.autograd import Variable
from char_rnn import CharRNN
class ProgressBar(object):
def __init__(self, total=100, stream=sys.std... |
from zipline.errors import UnsupportedPipelineOutput
from zipline.utils.input_validation import (
expect_element,
expect_types,
optional,
)
from .domain import Domain, GENERIC, infer_domain
from .graph import ExecutionPlan, TermGraph, SCREEN_NAME
from .filters import Filter
from .term import AssetExists, C... |
#!/usr/bin/env python
# ToMaTo (Topology management software)
# Copyright (C) 2010 Dennis Schwerdel, University of Kaiserslautern
#
# 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 versio... |
# This file is part of Radicale Server - Calendar Server
# Copyright © 2014 Jean-Marc Martins
# Copyright © 2012-2017 Guillaume Ayoub
# Copyright © 2017-2018 Unrud <unrud@outlook.com>
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... |
import cv2
import numpy as np
from moviepy.editor import VideoFileClip
from .logger import Log
from .calibration import GetCalibratedCamera, WarpMachine
from .filtering import EdgeDetector
from .lane_fitting import LaneFit
from .save import chmod_rw_all, delete_file
from .profiler import Profiler
def draw_overlay(wa... |
from rest_framework import serializers
from chigre.models import KegType
class KegTypeSerializer(serializers.ModelSerializer):
class Meta:
model = KegType
fields = ('id', 'name', 'size', 'pints', 'canyas')
|
import numpy as np
import pandas as pd
from calParser import obtainSchedule
from audit_parser import audit_info
from lsa_recommender import export_to_master,filter_available_classes
from decision_tree import preference_score,top_preferred_courses
from collaborative_filtering import loadAudits, inputData, buildRecommend... |
'''
File: property.py
Project: 08-class
File Created: Saturday, 25th July 2020 9:16:43 pm
Author: lanling (https://github.com/muyuuuu)
-----------
Last Modified: Saturday, 25th July 2020 9:16:46 pm
Modified By: lanling (https://github.com/muyuuuu)
Copyright 2020 - 2020 NCST, NCST
-----------
@ 佛祖保佑,永无BUG--
'''
# Python... |
# -*- coding: utf-8 -*-
import json
import os
import os.path
import logging
log = logging.getLogger(__name__)
def filelist(folderpath, ext=None):
'''
Returns a list of all the files contained in the folder specified by `folderpath`.
To filter the files by extension simply add a list containing all the e... |
'''
Copyright (C) 2016-2021 Mo Zhou <lumin@debian.org>
License: MIT/Expat
'''
import os
import math
import time
import random
from .cuda_selector import CudaSelector
RESOURCE_DEFAULT = 'void'
RESOURCE_TYPES = (RESOURCE_DEFAULT, 'virtual', 'cpu', 'memory', 'gpu', 'vmem')
if str(os.getenv('TASQUE_RESOURCE', '')):
RE... |
# -*- coding: utf-8 -*-
from wcstring import wcstr
import re
class PipelineTable(object):
'''
Pipeline Table Object.
Attributes
----------
data : 2-dimension list
1st dimension indicates the column
2nd dimension indicates the index, with combined
indexes grouped in a l... |
from itertools import groupby
from pathlib import Path
inp = Path('input.txt').read_text()
vowels = set('aeiou')
nope = 'ab cd pq xy'.split()
print(sum(
(
sum(c in vowels for c in line) >= 3 and
len(list(groupby(line))) < len(line) and
not any(s in line for s in nope)
)
for line ... |
import matplotlib.pyplot as plt
x_values = list(range(1, 5001))
y_values = [x**3 for x in x_values]
plt.scatter(x_values, y_values)
plt.show()
|
# 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 use ... |
from enum import Enum
import regex
from ..config import Config
from ..utils import Api
class OsuConsts(Enum):
"""
all constants related to osu
"""
# "": 0,
MODS = {
"NF": 1 << 0,
"EZ": 1 << 1,
"TD": 1 << 2,
"HD": 1 << 3,
"HR": 1 << 4,
"SD": 1 << 5,... |
"""
This file is part of L3Morpho.
L3Morpho 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 3 of the License, or
(at your option) any later version.
L3Morpho is distributed in ... |
# This program allows you to mark a square on the map using a two-digit system.
# The first digit is the vertical column number and the second digit is the horizontal row number.
row1 = ["⬜️", "⬜️", "⬜️"]
row2 = ["⬜️", "⬜️", "⬜️"]
row3 = ["⬜️", "⬜️", "⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
p... |
# -*- coding: utf-8 -*-
from django import template
import datetime
# import timedelta
register = template.Library()
def nice_repr(timedelta, display="long", sep=", "):
"""
Turns a datetime.timedelta object into a nice string repr.
display can be "minimal", "short" or "long" [default].
>>> f... |
'''
Escreva um programa que converta uma temperatura
digitada em °C e converta em °F.
'''
c = float(input('Digite a temperatura em °C: '))
f = (9*c + 160)/5
print(f'A temperatura de {c}°C é {f}°F!')
|
import logging
import numpy as np
import pandas as pd
import scipy.special
import scipy.stats
def encode_array(vals, sep=',', fmt='{:.6g}'):
return sep.join(map(fmt.format, vals))
def decode_array(vals, sep=','):
return np.asarray(list(map(float, vals.split(','))))
def encode_matrix(vals, sep1=',', sep2=';'... |
import unittest
import sys
sys.path.insert(0, '../')
from view_header import Route, PresentView, Flash, MSG_TYPE
class TestRoute(unittest.TestCase):
r1 = Route(True, 'test', {})
r2 = Route(True, 'test', {0:1, 1:'obj'})
def test_is_redirect(self):
self.assertEqual(self.r1.is_redirect(), True)
... |
from datetime import datetime
def from_iso8601(date):
return datetime.fromisoformat(date)
def to_iso8601(year, month, day, hour, minute, second):
return datetime(year, month, day, hour,
minute, second, 0).isoformat()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-17 06:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0007_auto_20171005_1713'),
]
operations = [... |
#
# Copyright Bernhard Firner, 2019-2020
#
# Ship class and supporting classes
from collections import OrderedDict
from enum import Enum
import torch
from dice import ArmadaDice
from game_constants import (
ArmadaDimensions,
ArmadaTypes
)
class UpgradeType(Enum):
commander = 1
officer ... |
import os
import sys
import time
import wave
import numpy as np
from datetime import datetime
from pyaudio import PyAudio, paInt16
class GenAudio(object):
def __init__(self):
self.num_samples = 2000 # pyaudio内置缓冲大小
self.sampling_rate = 8000 # 取样频率
self.level = 1500 # 声音保存的阈值
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.