content
stringlengths
5
1.05M
from xsklearn.transformers.text_vectorizers.bag_of_embeddings import ( # noqa: F401 BagOfEmbeddings, ) from xsklearn.transformers.text_vectorizers.scdv import SCDV # noqa: F401 from xsklearn.transformers.text_vectorizers.text_vectorizer import ( # noqa: F401 TextVectorizer, ) from xsklearn.transformers.text_...
#!/usr/bin/env python import os,argparse,yaml ''' Author: Pengjia Zhu (zhupengjia@gmail.com) ''' #input can be dictionary or yaml filename class Config(dict): ''' Configuration file read from yaml, inherit from python dictionary Input: - cfginput: yaml filepath, python dictionary,...
import click import sqlite_utils from bundesbank_to_sqlite.utils import save_banking_data @click.group() @click.version_option() def cli(): "Convert Bundesbank blz data to a SQLite database" @cli.command() @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), ...
import requests import wx import time import qrcode import json from singleton import Singleton from app_context import AppContext from pubsub import pub class BilibiliUtils(Singleton): def __init__(self) -> None: self.context = AppContext() self.request = requests.session() self.config = ...
# -*- coding: utf-8 -*- import re from pyndf.constants import CONST from pyndf.logbook import Logger from pyndf.utils import Utils from pyndf.process.data.records.excel.mission import Indemnite, Mission class Record(Logger, Utils): regexes = { "total": re.compile(r".*(?P<montant>Montant.*)(?P<indice>\d{5}...
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Layer from models.layers import CodeEmbedding, GraphConvolution, Encoder, HierarchicalDecoder, Decoder class SherbetFeature(Layer): def __init__(self, conf, hyper_params, name='sherbet_feature'): super().__init...
from django.conf import settings from django.contrib.auth.models import check_password from accounts.models import UserCred class EmailAuthBackend(object): """ A custom authentication backend. Allows users to log in using their email address. """ def authenticate(self, email=None, password=None, db='u...
# -*- mode: Python;-*- # You can run this .tac file directly with: # twistd -n --pidfile client.pid -y simple_client.tac from twisted.spread import pb from twisted.application.internet import TCPClient from twisted.application.service import Application import txtraits import enthought.traits.api as traits def on...
import numpy as np from scipy.io import loadmat from ..logger import logger from ..config import config, default from ..dataset import * def load_gt_roidb(dataset_name, image_set_name, dataset_path, flip=False): """ load ground truth roidb """ imdb = eval(dataset_name)(image_set_name, datas...
# Copyright (c) 2019. Partners HealthCare, Harvard Medical School’s # Department of Biomedical Informatics, Sergey Trifonov # # Developed by Sergey Trifonov and Michael Bouzinier, based on contributions by: # Anwoy Kumar Mohanty, Andrew Bjonnes, # Ignat Leshchiner, Shamil Sunyaev and other members of Division of G...
# -*- coding: utf-8 -*- """install skimage: pip install scikit-image -i https://pypi.tuna.tsinghua.edu.cn/simple """ from osgeo import gdal import numpy as np import time from skimage.transform import resize, rescale """read_raster:读取影像 write_raster:写入影像 raster_resize:resize/rescale""" # 读取ecw文...
from __future__ import absolute_import, print_function from cStringIO import StringIO import mock from changes.artifacts.base import ArtifactHandler from changes.artifacts.manager import Manager from changes.testutils import TestCase class ManagerTest(TestCase): @mock.patch.object(ArtifactHandler, 'process') ...
"""Constants. This module contains all constants for gilp (except for LP examples). """ __author__ = 'Henry Robbins' # Color Theme -- Using Google's Material Design Color System # https://material.io/design/color/the-color-system.html PRIMARY_COLOR = '#1565c0' PRIMARY_LIGHT_COLOR = '#5e92f3' PRIMARY_DARK_COLOR = '#...
import cv2 import numpy as np #import matplotlib.pyplot as plt from PIL import Image import json # code mostly from https://towardsdatascience.com/a-table-detection-cell-recognition-and-text-extraction-algorithm-to-convert-tables-to-excel-files-902edcf289ec def writecoords(imgfname, jsonfname): #read your file ...
# Scales the spectra by the same amount that the composite seds were scaled from astropy.io import ascii import pandas as pd import numpy as np import initialize_mosdef_dirs as imd from fit_emission import fit_emission def scale_spectrum(groupID, norm_method): '''Using the scaling on the photometry from convert_f...
# coding=utf-8 import argparse import io import os import shutil import time from pathlib import Path from PIL import Image, ImageDraw, ImageFont from openpyxl import load_workbook def load_defaults(table_path): """ Читает из таблицы настройки для обработки изображений :param table_path: str, путь до таб...
version = '0.5.0' homepage = 'https://github.com/authlib/loginpass'
"""Run simple server for previewing.""" import http.server import socketserver class server(socketserver.TCPServer): """Allow address to be re-used so that server can be restarted immediately.""" allow_reuse_address = True def run_server(options, root_dir): """Run web server on specified port.""" ...
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __title__ = 'autokeras' __author__ = 'JieYuan' __mtime__ = '19-1-3' """ import autokeras as ak # ak.MlpModule # # ak.ImageClassifier # ak.ImageRegressor # # ak.TabularClassifier # ak.TabularRegressor # ak.TextClassifier # ak.TextRegressor
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """This contains a class which is used to help generate `top_{name}.h` and `top_{name}.h`. """ from collections import OrderedDict from mako.template import Template from ...
import math from typing import Union, Tuple, List BOUNDS_TYPE = List[Union[Tuple, List]] # scipy.optimize style bounds [ (low,high), (low, high),... ] # Misc mappings that might be useful def positive_log_scale(u, low, high): """ Map u in (0,1) to (low,high) """ assert 0 <= u <= 1 assert 0 < low < high...
import os from django.conf.urls import url from django.contrib.staticfiles import utils from django.contrib.staticfiles.finders import BaseFinder from django.core.files.storage import FileSystemStorage from django.template import TemplateDoesNotExist from django.utils._os import safe_join from django.utils.datastructu...
"""COAP implementation using aiocoap.""" import asyncio import json import logging import socket from aiocoap import Message, Context from aiocoap.error import RequestTimedOut, Error, ConstructionRenderableError from aiocoap.numbers.codes import Code from aiocoap.transports import tinydtls from ..error import ClientE...
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from mock import Mock from sawmill.log import Log from sawmill.handler.distribute import Distribute def test_handlers_called(): '''Test that registered handlers are called.''' mock_handler_a = Mock() ...
from typing import Any, Callable, Iterable, Optional, List, Tuple, Union import torch from torch import jit, nn from torch.nn import functional as F # A high-order function. Wraps the input tuple for a function to process a time*batch*features sequence in batch*features (assumes one output) def bottle(f: Callable, x_...
#my take on tetris import pygame import random # creating the data structure for pieces # setting up global vars # functions # - create_grid # - draw_grid # - draw_window # - rotating shape in main # - setting up the main """ 10 x 20 square grid shapes: S, Z, I, O, J, L, T represented in order by 0 ...
''' Made By Sai Harsha Kottapalli Tested on python3 About : Port scanner with nmap Required: nmap module Use : identify hosts with nmap ''' import argparse import nmap from threading import * #grab banner screenLock = Semaphore(value = 1) #get hostname and traverse through individual ports. def nmapScan(host...
import shutil import logging import os import subprocess import zipfile import click import alfredcli.util logger = logging.getLogger(__name__) project_root = os.path.realpath('.') project_name = os.path.basename(project_root) archive_path = os.path.join(project_root, project_name + '.alfredworkflow') @click.gro...
import random import numpy as np import matplotlib.pyplot as plt from matplotlib import style from sklearn.datasets.samples_generator import make_blobs style.use('ggplot') X, y = make_blobs(n_samples=100, centers=3, n_features=2) colors = 10*['g', 'r', 'c', 'b', 'k'] class Mean_Shift: def __init__(self, radius=N...
#!/usr/bin/env python # In[1]: import os import sys module_path = os.path.abspath('.') if module_path not in sys.path: sys.path.append(module_path) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.backends.cudnn as cudnn from torch.autograd impor...
from django.db import models from django.contrib.auth import get_user_model from django.conf import settings from experts.models import ExpertProfile, ExpertClass def get_custom_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class Messages(models.Model): author = models.OneTo...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from app.models.base_model_ import Model from app import util class Account(Model): """NOTE: This class is auto generated by the swagger code generator program. ...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class SimplePerson(db.Model): __tablename__ = "simple_people" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) age = db.Column(db.Integer) bio = db.Column(db.String(2000))
"""Module extending the functionality of the abc standard library module.""" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=W0622 from __future__ import unicode_literals # noinspection PyPep8Naming class abstractclassmethod(classmethod): """Decorator to indicate that a class-method needs to be...
from openflix import config from .ygg import YGGProvider from .tracker import YGGTracker ygg = YGGProvider(**config.get_section("ygg")) tracker = YGGTracker(**config.get_section("tracker")) def query_content(details, options): return list(ygg.query_content(details, options))
from django.urls import path from .views import index, contato, produto # O ponto é do módulo core urlpatterns = [ path('', index, name='index'), # Se for na raiz mando pro index path('contato', contato, name='contato'), # Se for no contato manda pro contato path('produto/<int:pk>', produto, name='xuxa...
from .constants import * from .config import resolve_data_config from .dataset import Dataset, DatasetTar, AugMixDataset, DeepFakeDataset_v1, DeepFakeDataset_v2, DeepFakeDataset_v3, \ ConcatDataset from .transforms import * from .loader import create_loader, create_deepfake_loader, create_deepfake_loader_v1, create...
#-*- coding: utf-8 -*- from flask_admin.form import rules from logpot.auth.models import User from logpot.admin.base import AuthenticateView, CommonModelView class UserModelView(AuthenticateView, CommonModelView): column_list = ( 'name', 'email', 'password', 'updated_at' ) ...
"""OpenID Connect identity provider support.""" from __future__ import annotations from typing import TYPE_CHECKING from gafaelfawr.exceptions import ( DeserializeException, InvalidClientError, InvalidGrantError, UnauthorizedClientException, ) if TYPE_CHECKING: from typing import Optional f...
from __future__ import absolute_import from __future__ import division from builtins import zip from builtins import object import pandas as pd import numpy as np import json from ..misc import all_confignames, json_to_file import string import copy import os import glob def generate_condition_from_dict(cond_dict): ...
import configparser import os from dateutil import parser import pytz __SECRET_CONFIG_FILE = 'config/general/secrets.conf' log_config_files = { 'PRODUCTION': 'production.conf', 'TESTING': 'testing.conf', } config_files = { 'PRODUCTION': 'production.conf', 'TESTING': 'testing.conf', } def get_lo...
def bake(): '''Bake dynamic paint image sequence surface ''' pass def output_toggle(output='A'): '''Add or remove Dynamic Paint output data layer :param output: Output Toggle :type output: enum in ['A', 'B'], (optional) ''' pass def surface_slot_add(): '''Add a new Dynamic...
import math import os import matplotlib.pyplot as plt import pandas as pd def get_history(source: str) -> pd.DataFrame: history_dfs = [ pd.read_json(os.path.join(source, filename)) for filename in sorted(os.listdir(source)) ] history = pd.concat(history_dfs, ignore_index=True).reset_index() r...
""" *Split* """ from dataclasses import dataclass import jax.numpy as jnp from ._operator import SplitOperator __all__ = ["Split"] @dataclass class Split( SplitOperator, ): operator = jnp.split
from collections import namedtuple from functools import reduce from os import stat import numpy as np from itertools import product from numpy.core.fromnumeric import prod Pair = namedtuple("Pair", ["left", "right", "depth"]) def parse_pair(string, depth=0): if string[1].isnumeric(): left = int(string[...
import jwt from fastapi import Depends, HTTPException, Security from fastapi.security import OAuth2PasswordBearer from jwt import PyJWTError from sqlalchemy.orm import Session from starlette.status import HTTP_403_FORBIDDEN oauth2_parsed = OAuth2PasswordBearer(tokenUrl="/api/v1/token") def get_current_user( ...
import django_filters from rest_framework.permissions import IsAdminUser, IsAuthenticated from api.permissions import BookLoanCreatePermission, BookLoanObjectOwner from api.serializers import BookSerializer, AuthorSerializer, BookLoanSerializer, BookLoanCreateRequestSerializer from api.models import Book, Author, BookL...
#!usr/bin/python3 import getopt import sys import codecs def main(argv): infile = '' outfile = '' try: opts, args = getopt.getopt(argv, "hi:o:", ["infile=", "outfile="]) except getopt.GetoptError: print('SCRIPT -i <inputfile> -o <outputfile>') sys.exit(1) for opt, arg in ...
import logging from dbox import DropboxRemote from util import hassio_request, list_snapshots class SnapshotManager(object): def __init__(self, config): # instantiate and assign multiple uploaders (remotes) self.LOG = logging.getLogger("snapshot_manager") self.remotes = [] if conf...
# Copyright 2020 Adap GmbH. 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 ag...
#!/usr/bin/python3.5 import os import sys import re import xml.sax import tkinter as tk from tkinter import filedialog from tkinter import ttk from tkinter import * import tkinter.filedialog import tkinter.messagebox from tkinter.ttk import * from . import dialog from .dialog import Dialog from tkinter.filedialog impor...
# %% import requests import json # %% # ## Constants organization_name = 'oceanprotocol' UNAME = "" UPASS = "" # %% # ## Get the access token url = r'https://hub.docker.com/v2/users/login/' headers = None data = {'username': UNAME, 'password': UPASS} params = None r = requests.get(url, headers=headers, data=data, p...
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import str from builtins import int from future import standard_library standard_library.install_aliases() from avatar.targets.target import Target from avat...
# coding: utf-8 # (C) Copyright IBM Corp. 2021. # # 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...
#!/usr/bin/python # Modified by james lewis (@baldengineer) # MIT License # 2020 # Script to connect to Multicomp Pro MP730026 by BLE with the Bleak Module # Based on bleak example # Requires mpp730026_decode_bytearray.py to be in the same directory import logging import asyncio from sys import platform ...
from django.apps import AppConfig class AvaliacaoadConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'avaliacaoAD'
prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " cities = [] dict_city = {} while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!") cities.append(city) dict_c...
# workaround for a circular imports problem # e.g. if you import rpython.annotator.listdef first import rpython.annotator.model
def sale_price(original, discount): return round((1 - discount/100) * original, 2) print(input("Product: ")+ " on sale for "+ "$"+str(sale_price(float(input("Original price ($): ")), float(input("Discount (%): "))))+".")
# TODO disabled features # from flask_talisman import Talisman # def init_app(app): # # need to run with disable debug # talisman = Talisman(app)
#!~/.pyenv/shims/python """ Copyright Netherlands eScience Center Function : Quantify atmospheric meridional energy transport from EC-earth (Cartesius) Author : Yang Liu Date : 2017.12.07 Last Update : 2018.10.02 Description : The code aims to calculate the atmospheric meridional ener...
from django.db.models import query from django.shortcuts import redirect, render from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.shortcuts import re...
from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('<int:R_id>', views.dds,name='dds') ]
import os import shutil import glob from stat import S_IRUSR, S_IWUSR, S_IXUSR, S_IXGRP, S_IXOTH from .exchange import Exchange from ..utils import notebook_hash class ExchangeReleaseFeedback(Exchange): def init_src(self): self.src_path = os.path.join(self.coursedir.root, self.coursedir.feedback_directo...
# coding=utf-8 # # pylint: skip-file """ Copyright (c) 2019, Alexander Magola. All rights reserved. license: BSD 3-Clause License, see LICENSE for more details. """ import os import pytest from tests.common import asRealConf from zm import utils from zm.autodict import AutoDict from zm.buildconf.paths import ConfP...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('services', '0029_therapy'), ] operations = [ migrations.DeleteModel( name='Address', ), migratio...
import typing from abaqusConstants import * from .BoundaryCondition import BoundaryCondition from ..Region.Region import Region class PorePressureBC(BoundaryCondition): """The PorePressureBC object stores the data for a pore pressure boundary condition. The PorePressureBC object is derived from the BoundaryC...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from settings import * DEBUG = False ALLOWED_HOSTS = ['djangovpshosting.com']
''' Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: LFUCache(int capacity) Initializes the object with the capacity of the data structure. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1. void put(int key, in...
#!/usr/bin/env ipython # Saves me quite a bit of typing during interactive # testing sessions. # Just execute. import sys sys.path.append('.') from stackexchange import * from stackauth import * #so = Site(StackOverflow, '1_9Gj-egW0q_k1JaweDG8Q') so = Site(StackOverflow, 'pXlviKYs*UZIwKLPwJGgpg((')
from typing import Iterable, Type, Union from caplena.api import ApiBaseUri, ApiVersion from caplena.configuration import Configuration from caplena.controllers import ProjectsController from caplena.http.http_client import HttpClient, HttpMethod, HttpRetry from caplena.http.requests_http_client import RequestsHttpCli...
# -*- coding: utf-8 -*- # Zilliqa Python Library # Copyright (C) 2019 Gully Chen # MIT License import pytest from pprint import pprint from zillipy .zilliqa import chain from zillipy .account import Account from zillipy .contract import Contract def path_join(*path): import os cur_dir = os.path.dirname(os....
import os import earhart.plotting as ep from earhart.paths import RESULTSDIR basedata = 'fullfaint_edr3' # basedata = 'extinctioncorrected' # NOTE TODO PLOTDIR = os.path.join(RESULTSDIR, 'gaia_ruwe_vs_apparentmag') if not os.path.exists(PLOTDIR): os.mkdir(PLOTDIR) ep.plot_ruwe_vs_apparentmag(PLOTDIR, basedata=ba...
from tkinter import * from PIL import Image, ImageTk import hashlib import fileinput import user_reco def Space(): br = Label(root, text = "", bg = "black") br.pack() class User_Data: def __init__(self, pwd, temp, umd, wind,mail): self.pwd = pwd self.temp = temp self.umd = umd ...
"""Inertia Weight Functions""" import random def chaotic_inertia_weight(c1, c2, z, max_iter, current_iter): """Introduced by Feng et al. 2008""" z = 4 * z * (1-z) return (c1-c2)*((max_iter-current_iter)/max_iter)+(c2*z) def constant_inertia_weight(c): try: c != None return c excep...
import uuid import django.contrib.admin import django.db.models class Scan(django.db.models.Model): scan_id = django.db.models.UUIDField(primary_key=True, default=uuid.uuid4) scan_url = django.db.models.URLField(max_length=300) format_id = django.db.models.URLField(max_length=30, null=True) start_tim...
import pytest from mitmproxy.net.http import Headers from mitmproxy.net.http import multipart def test_decode(): boundary = 'somefancyboundary' content = ( "--{0}\n" "Content-Disposition: form-data; name=\"field1\"\n\n" "value1\n" "--{0}\n" "Content-Disposition: form-d...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC fr...
"""Test the views for cricket statistics.""" import pytest from django_cricket_statistics.views import BattingAverageSeasonView from django_cricket_statistics.models import Player @pytest.fixture def player(db): return Player.objects.create( first_name="John", nickname="Jack", middle_nam...
import numpy as np ACCEPTABLE_RADII = 2000 ACCEPTABLE_POLY_DELTA = 80 LANE_WIDTH = 5 MAX_CONS_BAD_MEAS = 5 IMSHAPE = np.array([720,1280,3]) SRC_POINTS = np.float32([[540, 445], [750, 445], [1130, 700], [200,700]]) DST_POINTS = np.float32([[0,0], [IMSHAPE[1], 0], [IMSHAPE[1], IMSHAPE[0]], [0, IMSHAPE[0]]])
import unittest from candle.tpl.util import * class TestModule(unittest.TestCase): def test_train_test_set(self): train_set, test_set = train_test_set()
import os BASE_CONFIG = { "GLOBUS_NATIVE_APP": "417301b1-5101-456a-8a27-423e71a2ae26", "GLOBUS_CC_APP": "21017803-059f-4a9b-b64c-051ab7c1d05d", "GLOBUS_SCOPE": "https://auth.globus.org/scopes/21017803-059f-4a9b-b64c-051ab7c1d05d/demo", "DEPENDENT_SCOPES": { "deriva_all": { "https:/...
#!/usr/bin/python # Start by importing the libraries we want to use import RPi.GPIO as GPIO # This is the GPIO library we need to use the GPIO pins on the Raspberry Pi import urllib2 # To send GET request import time import datetime # This is our submitValue function def submitValue(name, base_url, value): try:...
import datetime import itertools import sqlalchemy as sa from sqlalchemy import Boolean from sqlalchemy import cast from sqlalchemy import DateTime from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import literal from sqlalchemy impo...
# Pip imports from rest_framework import serializers # App imports from ..models import VotingDetailsLog class VotingDetailsLogSerializer(serializers.ModelSerializer): class Meta: model = VotingDetailsLog fields = "__all__"
from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", type=str, default='MobileNetSSD_deploy.prototxt', help="path to Caffe 'deploy' prototxt file") ap...
# inspect a sentence fragment # USAGE EXAMPLE: python3 ./inspect.py vectors/bnc.txt vectors/dimensions.txt import sys import itertools import numpy as np from utils import read_vectors, read_dimensions, cosine_similarity, coherence vectors = read_vectors(sys.argv[1]) dimensions = read_dimensions(sys.argv[2]) threshol...
from django.core.mail import send_mail from django.template.loader import render_to_string from .settings import * from django.urls import reverse # https://github.com/mailgun/transactional-email-templates def welcome_email(manager): context = { 'username': manager.user.first_name, 'url': SITE_URL...
import clean_up_releases from constants import ARGUMENT_PARSER_CREATOR from make_release import make_release from release_type import ReleaseLevel, ReleaseType from version_info import get_version, set_version def clean_releases(): clean_up_releases.clean_up_version() clean_up_releases.clean_up_releases() d...
#!/usr/bin/env python3 from efmaral import align from cefmaral import ibm_print import sys, argparse, random, pickle, tempfile # Adapted from efmaral's align.py def do_align(f_name, rev_f_name, seed): verbose = True no_lower_case = False reverse = False null_prior = 0.2 lex_alpha = 1e-3 null_...
import sqlite3 import dateutil.parser from twython import Twython # Put your stuff in here APP_KEY = 'FILL_THIS_IN' APP_SECRET = 'FILL_THIS_IN' ACCESS_TOKEN = 'FILL_THIS_IN' ACCESS_SECRET = 'FILL_THIS_IN' # Put a tweet ID in here # See https://twitter.com/ftrain/status/848534224600694784 for example ORIGINAL_TWEET = ...
# Pagination constant DEFAULT_START = 0 DEFAULT_END = 100 DEFAULT_PAGE_SIZE = 10 # Supported earch engine GOOGLE_ENGINE = 'google' GOOGLE_SCHOLAR_ENGINE = 'google_scholar' BAIDU_ENGINE = 'baidu' BING_ENGINE = 'bing' YANDEX_ENGINE = 'yandex' EBAY_ENGINE = 'ebay' YAHOO_ENGINE = 'yahoo' HOME_DEPOT_ENGINE = 'home_depot' ...
from django.apps import AppConfig class EventRegistrationsConfig(AppConfig): name = 'event_registrations'
try: # Only available in python 3.3+ from unittest.mock import * except ImportError: from mock import *
from pyspark.ml.feature import Normalizer from pyspark import SparkContext from pyspark.sql import SQLContext sc = SparkContext("local", "samp") sqlContext = SQLContext(sc) data = sqlContext.read.format("libsvm").load("D:\Spark\spark-1.6.1-bin-hadoop2.6\data\mllib\sample_libsvm_data.txt") indexer = Normalizer(p...
""" Test the environment parser the creates SETTINGS """ import os from unittest.mock import patch from pytest import fixture, raises from lm_agent.config import init_settings @fixture def good_env(): """ A parseable environment """ env = {"LM2_AGENT_BACKEND_BASE_URL": "http://hello/"} with patc...
import asyncio import pytest @pytest.mark.asyncio async def test_set_key_can_be_get(cache): await cache.set("test", "Ok!") assert await cache.get("test") == "Ok!" @pytest.mark.asyncio async def test_set_key_can_be_dict(cache): await cache.set("test", {"hello": "world"}) assert await cache.get("test...
"""test_preprocess.py""" import unittest import numpy as np from impyute.util import preprocess from impyute.imputation.cs import mean # TODO:Some hacky ass code to handle python2 not having `ModuleNotFoundError` try: raise ModuleNotFoundError except NameError: class ModuleNotFoundError(Exception): pas...
"""Runs the Raykar et al. (2010) algorithm on the galaxy classification task. Matthew Alger The Australian National University 2016 """ import argparse import logging import time import h5py import matplotlib import matplotlib.pyplot as plt import numpy import sklearn import sklearn.decomposition import sklearn.metr...