content
stringlengths
0
894k
type
stringclasses
2 values
""" ABOTS: A Bunch Of Tiny Scripts ============================== The name of this project explains what it is, a bunch of tiny scripts. I find myself thinking of many different projects that all require some core functionality that many other projects can share. However, it must be laid down first before adding th...
python
from ..mapper import PropertyMapper, ApiInterfaceBase from ..mapper.types import Timestamp, AnyType __all__ = ['DismissCard', 'DismissCardInterface'] class DismissCardInterface(ApiInterfaceBase): card_id: int image_url: str title: AnyType message: AnyType button_text: AnyType camera_target: A...
python
# -*- coding: utf-8 -*- """ Created on Wed Apr 1 15:52:30 2020 @author: liu """ NAME = 'FCS' DESCR = """ This example uses **Pulse Streamer** to emulate signals for fluorescence correlation spectroscopy (FSC). The example demonstrates autocorrelation measurement with logarithmic binning. * Channel 1 - fluorescence...
python
# ___ _ ___ ___ _ | # / _ \ __| |_ ___| _ \/ __| | | Create 8-bit-like games! # | (_) / _| _/ _ \ _/ (_ |_| | Author: Death_Miner # \___/\__|\__\___/_| \___(_) | Version: 0.4.0 # | # # @ octopg/data.py => Handles multiple data files # We use the JSON format ...
python
__all__ = [ "same" , "same_attrs" # Can be used to implement interface of `same`. # __same__ = same_{implementation} , "same_vectors" , "same_sets" , "same_mappings" ] from types import ( GeneratorType ) from six.moves import ( zip_longest ) from collections import ( Mapping ) class End(objec...
python
from pathlib import Path from jinja2 import Environment from jinja2.loaders import BaseLoader from pathlib import Path import requests import json req = requests.get(r"https://raw.githubusercontent.com/thautwarm/DianaScript-JIT/master/sigs-for-builtin-modules.json") if req.status_code != 200: raise IOError("cannot re...
python
import torch from torch.utils.data import Dataset import numpy as np class MNISTGraphDataset(Dataset): def __init__(self, dataset_path, num_thresholded, train=True, intensities=True, num=-1): if(train): dataset_tr = np.loadtxt(dataset_path + 'mnist_train.csv', delimiter=',', dtype=np.float32) ...
python
# Copyright 2022 Huawei Technologies Co., Ltd # # 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...
python
from collections import Mapping, Iterable import copy as copy_ import numpy as np import datetime as dt from . import misc def select_var(d, name, sel): var_dims = list(d['.'][name]['.dims']) d['.'][name]['.dims'] = var_dims for key, value in sel.items(): if isinstance(value, Mapping): if len(sel) > 1: raise V...
python
import json import os from typing import Callable import imageio import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import pathlib import torch from torchvision import datasets, transforms from torchvision.datasets.mnist import read_label_file, read_image_file from args impor...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Blogs from .forms import Create def add_blog(request): if request.method == "POST": addBlog = Create(request.POST, request.FILES) if...
python
############################################################################### # Copyright (c) 2007-2018, National Research Foundation (Square Kilometre Array) # # Licensed under the BSD 3-Clause License (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy # of the ...
python
from typing import Sequence from deeppavlov.models.tokenizers.utils import detokenize from core.state_schema import Dialog from annotators.person.person_normalizer import PersonNormalizer class DefaultPostprocessor: def __init__(self) -> None: self.person_normalizer = PersonNormalizer(per_tag='PER') ...
python
# SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_bitmap_font.pcf` ==================================================== Loads PCF format fonts. * Author(s): Jeff Epler Implementation Notes -------------------- **Hardware:** **Software and Dependencies...
python
from instapy import InstaPy import random from time import sleep import subprocess ###################################### insta_username = 'your login' insta_password = 'your password' number_of_likes = 1200 number_of_follows = 0 number_of_comments = 250 tags = ['student', 'nature', 'river', 'forest', 'tree', 'lake',...
python
import argparse import timeit from statistics import fmean, variance from pyformlang.cfg import Terminal from src.cfg_algorithms import cyk from src.cnf import WeakCNF from src.label_graph import LabelGraph from src.rpq import rpq, rpq_with_linear_tc if __name__ == '__main__': parser = argparse.ArgumentParser( ...
python
#!/usr/bin/env python3 #Convert EPUB files to either single HTML or text files. #They can then be read on refreshable Braille displays, such as the Brailliant series from HumanWare or the Braille Edge by Hims. #Also works with the Victor Reader Trek/Stream by Humanware. #Requires pypandoc (shoutouts to @TheQuinbox on ...
python
import numpy as np import matplotlib.pyplot as plt from solar_parallel import solar from simulator import simul ########################################## # define the class 'the simulation_plot' # ########################################## ''' this class is used for plotting the result of the demon...
python
import os import cv2 import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm datasets_path = ["datasets/training", "datasets/testing", "datasets/validation"] categories = ["RAW", "FRET", "FORCE"] def get_main_bbox(image, threshold=100): _, image_th = cv2.threshold(image, threshold, 65535, cv2.TH...
python
""" Manage generation of maps from HEALpix tables $Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/pipeline/pub/display_map.py,v 1.3 2011/06/24 04:53:06 burnett Exp $ """ import os,sys, types, pickle import numpy as np import pylab as plt from uw.utilities import image from skymaps import Band, SkyDir, PySkyFu...
python
# Copyright 2019 Hewlett Packard Enterprise Development LP # 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...
python
""" Tests for PyBryt annotations """ import time import numpy as np from collections.abc import Iterable from functools import lru_cache from pybryt import Value from pybryt.utils import pickle_and_hash START_TIMESTAMP = 1614904732.51892 @lru_cache(1) def generate_memory_footprint(): """ """ np.rando...
python
""" Exteneral Device Specifications Sub-package """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government r...
python
# -*- coding: utf-8 -*- """The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Soft...
python
import os import json pathToFolder = "c:/Users/dilGoe/Desktop/Praktikum/django" pathToFile = "c:/Users/dilGoe/Desktop/Praktikum/django/LICENSE" def getCorpusFolder(pathToFolder=pathToFolder): resultDictJSON = {} for (dirpath, dirname, filename) in os.walk(pathToFolder): for file in filename: ...
python
"""Approval race condition mitigation.""" from web3.contract import Contract def test_increase_approval(released_token: Contract, customer: str, empty_address: str, allowed_party): """Increase approval.""" token = released_token amount = 5000 change = 1000 assert token.call().allowance(customer, ...
python
import unittest import time from selenium import webdriver from selenium.webdriver.common.keys import Keys class MonolithicTest(unittest.TestCase): def _steps(self): for name in dir(self): if name.startswith("step"): yield name, getattr(self, name) def assertBrowserTitle(...
python
import json from .measurementGroup import MeasurementGroup from .measurementItem import MeasurementItem from .codeSequences import CodeSequence class MeasurementReport(object): """ Data structure plus convenience methods to create measurment reports following the required format to be processed by the DCMQI tid...
python
from setuptools import setup, find_packages setup( name='pyhindsight', packages=find_packages(), include_package_data=True, scripts=['hindsight.py', 'hindsight_gui.py'], version='2.0.4', description='Internet history forensics for Google Chrome/Chromium', url='https://github.com/obsidianforensics/hindsigh...
python
from bs4 import BeautifulSoup import requests import re # function to get all the policy urls from a website def collect_url_links(url_link) -> list: url_list = [] pattern = re.compile(r'^http') source = requests.get(url_link).text soup = BeautifulSoup(source, 'lxml') a_tag = soup.find_all("a") ...
python
def diamond(n): """Display a diamond made of *. Args: n: (int) Amount of *s in the middle row. Returns: Diamond shaped text. None if input n is invalid. """ if n <= 0 or n % 2 == 0: return None offset = int((n - 1)/2) # for i in range(offset + 1): # shap...
python
# -*- coding: utf-8 -*- """ Created on Sun Oct 04 20:05:13 2015 Translation of octave code for CSAPS. @author: Kevin """ import numpy as np import scipy as sp from scipy import interpolate from scipy.sparse import linalg def csaps(x, y, p, xi=[], w=[]): # sort the inputs by ordering of x ii = np.argsort(x)...
python
__pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x09\x00\x61\x0d\x0d\x0a\x08\x2d\xa0\x01\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\x36\x1e\x00\x00\x00\x00\x00\x10\x12\xd8\xc1\xe3\xd7\xa8\xd7\xd4\xb7\xb9\xae\x4c\x5b\x3c\xd7\x05\x00\x00\x00\x00\x00\x00\x00\x00\x78\x44\x98\xc9\x9e\xe4\x19\x...
python
# 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. import types from recipe_engine.config import ( config_item_context, ConfigGroup, Single, Static) from recipe_engine.config_types import Path from . imp...
python
"""Test entry point""" import aiohttp import pyoctoprintapi import argparse import asyncio import logging from types import MappingProxyType LOGGER = logging.getLogger(__name__) async def main(host, user, port, use_ssl): """Main function.""" LOGGER.info("Starting octoprint") async with aiohttp.ClientSe...
python
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of CERN Search. # Copyright (C) 2018-2021 CERN. # # Citadel Search is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Signal Receivers.""" from flask import current_app fro...
python
from pyrosetta import * from roseasy.movers import constraint def insert_alas(pose, position, length, insert_after=True, reset_fold_tree=True, fold_tree_root=1): '''Insert a poly-ALA peptide before or after a given position., Set the fold tree to have a cutpoint before or after inserted residues. Author: X...
python
#!/usr/bin/env python3 a, b, c, d = map(int, open(0).read().split()) print(abs(a-c) + abs(b-d) + 1)
python
""" Generate matched synthetic lesions dataset Authors: Chris Foulon & Michel Thiebaut de Scotten """ import os import argparse import random import numpy as np import json import csv import nibabel as nib import nilearn from nilearn.masking import compute_multi_background_mask, intersect_masks from nilearn.image imp...
python
# -*- coding: utf-8 -*- # !/usr/bin/python """ Created on Mar 18th 10:58:37 2016 train a continuous-time sequential model @author: hongyuan """ import pickle import time import numpy import theano from theano import sandbox import theano.tensor as tensor import os import sys #import scipy.io from collections import ...
python
from os import getenv from rockset import Client, Q, F rs = Client(api_key=getenv('ROCKSET_SECRET'), api_server='api.rs2.usw2.rockset.com') def after_req(response): cnt = rs.sql( Q('NewsArchivesHits').where(F['_id']=='News').select('count') )[0]['count'] rs.Collection.retrieve('NewsArchive...
python
from datetime import datetime from pydantic import BaseModel from pydantic import Field class TodoCreate(BaseModel): title: str = Field(..., min_length=4, max_length=50, example="My first task") class Todo(TodoCreate): id: int = Field(...) is_done: bool = Field(default=False) created_at: datetime =...
python
#!/usr/bin/env python3 ''' Copyright 2018, VDMS Licensed under the terms of the BSD 2-clause license. See LICENSE file for terms. /sapi/modify endpoint. Designed to initiate a sapi API user. ```swagger-yaml /custdashboard/modify/{dash_id}/ : get: description: | Modifies a custom audit by either adding, r...
python
import click import os from click.exceptions import ClickException from .dashboard import read_har_json, plot_har @click.command() @click.argument('path', type=click.Path(exists=True)) def plot(path): """ Plot HTTP Archive format Timings :param path: Path containing HAR specs in json files ...
python
import FWCore.ParameterSet.Config as cms DQMStore = cms.Service("DQMStore", enableMultiThread = cms.untracked.bool(True), saveByLumi = cms.untracked.bool(False), trackME = cms.untracked.string(''), verbose = cms.untracked.int32(0) )
python
import sys import math import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister class QFT: """ Class which generates the circuit to perform the Quantum Fourier Transform (or its inverse) as described in Mike & Ike Chapter 5. (Michael A Nielsen and Isaac L Chuang. Quant...
python
from breezycreate2 import _Create2 import time # A simple melody that plays every time the bot is connected to. MELODY = [('C4',11,0.3), ('C4',11,0.3), ('C4',11,0.3), ('C4',32,0.7), ('G4',32,0.7), ('F4',11,0.3), ('E4',11,0.3), ('D4',11...
python
""" This network is build on top of SNGAN network implementation from: https://github.com/MingtaoGuo/sngan_projection_TensorFlow.git """ from explainer.ops import * from tensorflow.contrib.layers import flatten import pdb def get_embedding_size(): return [64, 64, 4] class Generator_Encoder_Decoder: def __in...
python
# -*- coding: utf-8 -*- from Speak import JLing_Speak import sys if __name__ == '__main__': print(''' ******************************************************** * JLing - 中文语音对话机器人 * * (c) 2019 周定坤 <zhoudk@ccitrobot.com> * *****************************************...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-02-17 16:32 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('events', '0020_image_name'), ] operations = [ migrations.AlterUniqueTogether( ...
python
#!/usr/bin/env python import os import sys # build_path is mandatory, build_all is optional. if len(sys.argv) < 2: print "usage: %s [build_path> [build_all]" % sys.argv[0] sys.exit(1) # Build all is by default False. build_all = False if len(sys.argv) == 3 and sys.argv[2] == 'build_all': build_all = True build...
python
from django.shortcuts import get_object_or_404 from rest_framework import generics from mangacache.models import Chapter, Manga, Author from mangacache.serializers import AuthorSerializer, MangaSerializer, ChapterSerializer class AuthorList(generics.ListCreateAPIView): queryset = Author.objects.all() seriali...
python
#!/usr/bin/env python # Copyright 2015 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. """Small utility script to simplify generating bindings""" import argparse import os import subprocess import sys SCRIPT_DIR = os.pat...
python
import argparse import logging from http.server import HTTPServer, SimpleHTTPRequestHandler from socketserver import TCPServer class LoggingHandler(SimpleHTTPRequestHandler): def log_message(self, format, *args): logging.info(format % args) def webserve(): parser = argparse.ArgumentParser( d...
python
#Based on paper Predicting Protein-Protein Interactions by Combing Various Sequence- Derived Features into the General Form of Chou’s Pseudo Amino Acid Composition by Zhao, Ma, and Yin import os import sys #add parent and grandparent to path currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os...
python
load("//tools/base/bazel:bazel.bzl", "iml_module") load("//tools/base/bazel:kotlin.bzl", "kotlin_test") load("//tools/base/bazel:maven.bzl", "maven_java_library", "maven_pom") load("//tools/base/bazel:utils.bzl", "fileset", "flat_archive") load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar") load("//tools/base...
python
import sncosmo from astropy.cosmology import w0waCDM import numpy as np from lsst.sims.catUtils.dust import EBV import os from scipy.interpolate import griddata from sn_tools.sn_telescope import Telescope from lsst.sims.photUtils import Bandpass, Sed from astropy import units as u import pandas as pd from sn_tools.sn_i...
python
from random import randint from tools.population_creator import (ImpossibleToCompleteError, Individual, create_individual) def mutation(individual: Individual): """ :param individual: особь :return: возвращает мутировавшую особь Для мутации хромосомы сначала с ...
python
import os from django.conf import settings from pdf2image import convert_from_path class PdfRasterizer: def __init__(self): self._dpi = settings.PDF_RASTERIZER["dpi"] self._fmt = settings.PDF_RASTERIZER["format"] self._thread_count = settings.PDF_RASTERIZER["thread_count"] def raster...
python
''' This downloads the data about which locations Twitter provide top the top 10 trending item lists from and stores the data in the database ''' from TrendAnalyser import TrendAnalyser TA = TrendAnalyser() print TA._update_woeid_data()
python
# -*- coding: utf-8 -*- """ tests - helper functions ~~~~~~~~~~~~~~~~~~~~~~~~ test cases for olaf helper function :copyright: (c) 2015 by Vivek R. :license: BSD, see LICENSE for more details. """ import os import random import string import unittest from click.testing import CliRunner import olaf class Test...
python
import random from timeit import default_timer as timer from clkhash.key_derivation import generate_key_lists from clkhash.schema import get_schema_types from clkhash.bloomfilter import calculate_bloom_filters from clkhash.randomnames import NameList from anonlink.entitymatch import * from anonlink.util import popcou...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from conf.config import * import ssl import socket import os class Tool: def __init__(self): self.description = "Get the SSL certificate information" self.options = { 'domain': { "value": "", "required": Tru...
python
"""This module is a wrapper for the PuLP library, which is capable of solving LP/MILP instances by using different kinds of solvers (like Gurobi or CBC). The wrapper defines custom MILP and LP classes in order to simplify the instantiation of problems from coefficient vectors and matrices.""" from .solverresult impor...
python
# Copyright 2022 Masatoshi Suzuki (@singletongue) # # 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...
python
#!/usr/bin/python2 import sys import math import socket import random import time import errno # put-get flag to service success def service_up(): print("[service is worked] - 101") exit(101) # service is available (available tcp connect) but protocol wrong could not put/get flag def service_corrupt(): p...
python
from django.urls import path from . import views app_name = 'sqds_officers' urlpatterns = [ path('<str:api_id>/geotb/', views.GeoTBPlayerView.as_view(), name='geo_tb'), path('<str:api_id>/sepfarm/', views.SepFarmProgressView.as_view(), name='sep_farm') ]
python
import cv2 def undistort_image(img, mtx, dist): ''' Undistorts image given a camera matrix and distortion coefficients ''' undist_img = cv2.undistort(img, mtx, dist, None, mtx) return undist_img
python
lista_inteiros = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [9, 1, 8, 9, 9, 7, 2, 1, 6, 8], [1, 3, 2, 2, 8, 6, 5, 9,6, 7], [3, 8, 2, 8, 6, 7, 7, 3, 1, 9], [4, 8, 8, 8, 5, 1, 10, 3, 1, 7], [1, 3, 7, 2, 2, 1, 5, 1, 9, 9], [10, 2, 2, 1, 3, 5, 1, 9, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ] def encont...
python
# Copyright 2015-2018 Capital One Services, LLC # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from ..azure_common import BaseTest, arm_template, cassette_name from c7n_azure.resources.key_vault import (KeyVaultUpdateAccessPolicyAction, WhiteListFilter, ...
python
from django.apps import AppConfig class ScalprumConfig(AppConfig): name = 'scalprum'
python
from typing import cast import pytest from parse import compile from json import dumps as jsondumps from behave.model import Table, Row from grizzly.context import GrizzlyContext from grizzly.types import RequestMethod, RequestDirection from grizzly.tasks import TransformerTask, LogMessage, WaitTask from grizzly.tas...
python
from enum import Enum from parse import parse from datetime import datetime import json class CDFLogType(Enum): NEW_COREHDF_INSTANCE = 1 PERSON_DETECTED = 2 NOTHING_DETECTED = 3 CANNOT_BE_INFERRED = 4 class CDFLog: def __init__(self, logfile: str = 'log.txt'): self.file_handler = open(lo...
python
# -*- coding: utf-8 -*- """ NAME: github-reqs.py AUTHOR: Ulyouth VERSION: 1.0.0 DATE: 15.10.2020 DESC: A PyBullet-based script to check which GitHub logins are valid using requests library. """ from chkutils import ChkUtils def chkMain(ss, test, rst, captcha, data): # Good pract...
python
def build_nn(params): seq_length, vocabulary_size, layers, embedding_dim, upside_dim, downside_dim, lr, dropout = \ params['seq_length'], params['vocabulary_size'], params['layers'], params['embedding_dim'], params['upside_dim'], params['downside_dim'], params['lr'], params['dropout'] from tensorflow.k...
python
import numpy as np from keras.datasets import cifar10 from keras.models import Sequential, Model from keras.layers import Input, Dense, LeakyReLU, BatchNormalization, ReLU from keras.layers import Conv2D, Conv2DTranspose, Reshape, Flatten from keras.optimizers import Adam from keras import initializers from keras.utils...
python
#!/usr/bin/env python import os import sys import glob import hashlib import itertools sys.path.insert(0, os.pardir) from testing_harness import PyAPITestHarness import openmc class TallySliceMergeTestHarness(PyAPITestHarness): def _build_inputs(self): # The summary.h5 file needs to be created to read i...
python
from onnxquantizer import Quantizer import config as cfg import os import cv2 import numpy as np def prehandle(img_path, dst_size): img = cv2.imread(img_path, cv2.IMREAD_COLOR) resized = cv2.resize(img, dsize=(dst_size[1], dst_size[0]), interpolation=cv2.INTER_LINEAR) return resized def main(): #l...
python
import logging import logging.config def configure_logging(config, disable_existing=False): """ Set up (process-global!) loggers according to given app configuration. Look for 'logging' key in [app] config section, which should be the path to a logging config file in the format expected by logging.co...
python
# A simple demo of the mesh manager. # Generates and renders a single tile with some ferns and trees # # INSTRUCTIONS: # # Launch from outside terrain, meaning launch with: # python terrain/meshManager/main.py import sys sys.path.append(".") from panda3d.core import * from panda3d.core import Light,AmbientLight,Dire...
python
import os import re import discord from discord import MessageType from discord.commands import slash_command, Option, message_command from discord.ext import commands from sqlalchemy import desc from . import XpSys import PictureCreator from PictureCreator.utils import ConvrterToCI from models.Emojies import Emojie f...
python
config = { "--beam-delta":[0.5,float], "--delta":[0.000976562,float], "--determinize-lattice":['true',str], "--hash-ratio":[2,float], "--minimize":['false',str], "--phone-determinize":['true',str], "--prune-interval":[25,int], ...
python
import socket from unittest import TestCase from ..subprocess_server_manager import SubprocessServerManager, SubprocessServer from ..exceptions import ImproperlyConfigured class BaseSocketTestCase(TestCase): @ staticmethod def get(host: str, port: int) -> bytes: with socket.socket(socket.AF_INET, sock...
python
from builtins import zip from builtins import range from builtins import object import os import numpy as np import warnings import matplotlib.pyplot as plt import rubin_sim.maf.utils as utils __all__ = ['applyZPNorm', 'PlotHandler', 'BasePlotter'] def applyZPNorm(metricValue, plotDict): if 'zp' in plotDict: ...
python
''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import import multiprocessing from gensim.models import Doc2Vec class MyDoc2Vec(object): def __init__(self, dim, hs=0, window=5, negative=5, epoches=5, dm=1, dm_concat=1): super(MyDoc2Vec, self).__init__() self.dim = dim ...
python
# -*- coding: utf-8-*- import random import re import sys sys.path.append('/home/pi/Desktop/autoh/Lights') from serial_led import serialControl WORDS = ["TURN", "THE", "LIGHT", "ON"] def lightno(mic): text=mic.activeListen() if text=="ONE" or text=="1": mic.say("Turning light one on") serialControl("2000") e...
python
#!/usr/bin/python3 # Copyright 2022 Sam Steele # # 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...
python
import copy import enum import logging from pathlib import Path import re __version__ = "0.0.9" __author__ = "rigodron, algoflash, GGLinnk" __license__ = "MIT" __status__ = "developpement" # raised when the action replay ini file contains a bad formated entry class InvalidIniFileEntryError(Exception): pass # raised...
python
# unittest for cal.py import unittest import cal class TestCal(unittest.TestCase): def test_add(self): result = cal.add(10,5) self.assertEqual(result, 15) if __name__ == '__main__': unittest.main() # to avoid using this if statement below; run python -m unittest test_cal.py
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcapiprodDrawndnContractGetResponse(AlipayResponse): def __init__(self): super(AlipayEcapiprodDrawndnContractGetResponse, self).__init__() self._contract_conten...
python
""" # Data Structures and Algorithms - Part B # Created by Reece Benson (16021424) """ from tennis import Round from tennis.Colours import Colours class Tournament(): # Variables name = None game = None parent = None json_data = None rounds = None gender = None difficulty = None p...
python
#-*- encoding: utf-8 -*- """ Ordered fractions Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1...
python
from enum import Enum ISO8601_FMT = "%Y-%m-%dT%H:%M:%S.%fZ" DATE_FORMAT = "%Y-%m-%d" ALL_CASES_QUEUE_ID = "00000000-0000-0000-0000-000000000001" UPDATED_CASES_QUEUE_ID = "00000000-0000-0000-0000-000000000004" ENFORCEMENT_XML_MAX_FILE_SIZE = 1000000 # 1 MB class GoodSystemFlags: CLC_FLAG = "00000000-0000-0000-0...
python
import pytest import case_conversion.utils as utils from case_conversion import Case, InvalidAcronymError @pytest.mark.parametrize( "string,expected", ( ("fooBarString", (["foo", "Bar", "String"], "", False)), ("FooBarString", (["Foo", "Bar", "String"], "", False)), ("foo_bar_string",...
python
from weibo import APIClient import json APP_KEY = "3722673574" APP_SECRET = "3686fea0a65da883b6c2a7586f350425" CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) with open('token.json', 'r') as f: r = json.load(f) a...
python
#!/usr/bin/env python3 # -+- coding: utf-8 -*- import re import json import hashlib from os import path, makedirs, SEEK_CUR from harvester import libDataBs def getOrCreatePath(archive_base_path): if not path.exists(archive_base_path): makedirs(archive_base_path) def setUpDir(site, archive_base_path): ...
python
from collections import OrderedDict import itertools import json from scipy.sparse import coo_matrix, block_diag import autograd.numpy as np from .base_patterns import Pattern #################### # JSON helpers. # A dictionary of registered types for loading to and from JSON. # This allows PatternDict and PatternA...
python
class Recall: def __init__(self, max_count=10): self.max_count = max_count self.position = 0 self.buffer = [] def move_up(self): if self.position < len(self.buffer) - 1: self.position += 1 return self.buffer[self.position] def move_down(self): ...
python
# https://leetcode.com/problems/3sum/ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = set() nums = sorted(nums) for k in range(0, len(nums)): target = -(nums[k]) l, r = k+1, len(nums)-1 while(l<r):...
python
from django.apps import AppConfig class GradedConfig(AppConfig): name = 'graded'
python