content
stringlengths
5
1.05M
import os from app import DATA_DIR from app.bq_service import BigQueryService from app.file_storage import FileStorage from app.bot_communities.tokenizers import Tokenizer #, SpacyTokenizer from app.bot_communities.token_analyzer import summarize_token_frequencies from pandas import DataFrame if __name__ == "__main...
word_count = {} with open("./Beginner Guide to Python.txt") as fin: for line in fin: line = line[:-1] words = line.split() for word in words: if word not in word_count: word_count[word] = 0 word_count[word] += 1 print( sorted( word_count....
from collections import namedtuple import torch from torch.nn import LSTMCell, Module, Linear from editor_code.copy_editor.vocab import base_plus_copy_indices from gtd.ml.torch.seq_batch import SequenceBatch from gtd.ml.torch.source_encoder import MultiLayerSourceEncoder from gtd.ml.torch.utils import NamedTupleLike ...
# generated with make_mock.py E2BIG = 7 EACCES = 13 EADDRINUSE = 98 EADDRNOTAVAIL = 99 EADV = 68 EAFNOSUPPORT = 97 EAGAIN = 11 EALREADY = 114 EBADE = 52 EBADF = 9 EBADFD = 77 EBADMSG = 74 EBADR = 53 EBADRQC = 56 EBADSLT = 57 EBFONT = 59 EBUSY = 16 ECHILD = 10 ECHRNG = 44 ECOMM = 70 ECONNABORTED = 103 ECONNREFUSED = 11...
import numpy as np """ How to use? example 1: # J = [[-1,0,0],[0,2,1],[0,0,2]] # make_problem_Jordan_normal_form(J) example2: J = [[-1,0,0,0],[0,2,1,0],[0,0,2,1],[0,0,0,2]] make_problem_Jordan_normal_form(J,difficulty=8) """ """ テキトーな n*n ユニモジュラ行列を1つ得る (単位行列に対して、行or列変形をランダムに繰り返すというアルゴリズム) difficulty: ユニモジュラ行列の「複雑度」...
import ast import os import collections from nltk import pos_tag def flat(_list): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in _list], []) def is_verb(word): """return True if word is a verb, base form""" return word is not None and pos_tag([word])[0][1] == 'VB' def is_sp...
import logging def config_log(level): logging.basicConfig( format='%(asctime)s %(name)s %(levelname)s %(message)s', level=level.upper())
import random import numpy as np from .arena import Arena from .deliverylogger import DeliveryLogger from .drone import Drone class PackageGenerator: def __init__(self): self.coordinate_pool = self.define_coordinate_pool() self.pool_size = self.coordinate_pool.shape[0] self.package_weights...
from rest_framework import serializers from ..models import Officer from accounts.models import User from accounts.api.serializers import AccountSerializer, AccountCreateSerializer, AccountLoginSerializer from django.contrib.auth import get_user_model from django.db.models import Q from ..models import Officer # c...
a = 100 b = 10 c = 5 over
def main(): x=2 y=6 print(plus(x,y)) def plus(x,y): return x+y if __name__ == "__main__": main()
"""Test dataset building and splitting.""" import pytest import torch from gcn_prot.data import get_datasets, get_longest def test_longest(graph_path): """Test get longest length in directory.""" assert 189 == get_longest(graph_path) def test_get_dataset(data_path): """Test splitting with default size...
#!/usr/bin/env python3 # @Time : 17-9-8 23:48 # @Author : Wavky Huang # @Contact : [email protected] # @File : io.py """ Process input and output """ import calendar import json import os import pickle from datetime import date from urllib import request from mhcalendar.time_elements import Schedule, Holiday, M...
import os import itertools import glob import re import torch from torch.utils.data import Dataset import torchvision import torchvision.transforms as transforms import torchvision.transforms.functional as F import PIL from PIL import Image import cv2 import numpy as np import matplotlib.pyplot ...
import unittest import numpy as np import openmdao.api as om from openmdao.utils.assert_utils import assert_check_partials from openaerostruct.aerodynamics.lift_drag import LiftDrag from openaerostruct.utils.testing import run_test, get_default_surfaces class Test(unittest.TestCase): def test(self): su...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== # Make sure the binaries can be imported import os import sys sys.path.append(os.pa...
from dataclasses import dataclass from .t_event import TEvent __NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL" @dataclass class Event(TEvent): class Meta: name = "event" namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL"
# Copyright (c) 2013, Noah Jacob and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt def execute(filters=None): columns, data = [], [] date=[] labels = "" if filters.get('filter_based_on') =='Date Range': date.appe...
from typing import Iterable, Optional from crowdin_api.api_resources.abstract.resources import BaseResource from crowdin_api.api_resources.labels.types import LabelsPatchRequest class LabelsResource(BaseResource): """ Resource for Labels. Link to documentation: https://support.crowdin.com/api/v2/#ta...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """Planet aggregator library. This package is a library for developing web sites or software that aggregate RSS, CDF and Atom feeds taken from elsewhere into a single, combined feed. """ __version__ = "1.0~pre1" __authors__ = [ "Scott James Remnant <[email protected]>", ...
""" По данному натуральном n вычислите сумму 1²+2²+3²+...+n². Формат ввода Вводится натуральное число. Формат вывода Выведите ответ на задачу. """ n = int(input()) k = 0 for i in range(n+1): k += i ** 2 print(k)
#!/usr/bin/env python import logging from scanpy_scripts.wrapper_utils import ( ScanpyArgParser, comma_separated_list, read_input_object, write_output_object, ) def main(argv=None): argparser = ScanpyArgParser(argv, 'Run Louvain clustering on data with neighborhood graph computed') argparser.add_inp...
""" Alex Martelli's Borg non-pattern - not a singleton See: http://www.aleax.it/5ep.html """ import logging # import en_core_web_lg import en_core_web_md from gamechangerml.src.utilities.borg import Borg logger = logging.getLogger(__name__) class SpacyConfig(Borg): def __init__(self): Borg.__init__(se...
import unittest class MainTestCase(unittest.TestCase): def test_two_and_two(self): four = 2 + 2 self.assertEqual(four, 4) self.assertNotEqual(four, 5) self.assertNotEqual(four, 6) self.assertNotEqual(four, 22) if __name__ == '__main__': unittest.main()
#NODE. THIS GETS THE FILE NAME FROM THE SERVER AND SENDS THE FILE BACK import socket s = socket.socket() host = socket.gethostname() port = 7013 s.bind((host,port)) s.listen(5) print("<<-NODE IS UP->>") while True: connection, address = s.accept() #Accepts the connection from the server print("Node is connec...
import asyncio import logging import random import threading from typing import Callable, Optional import discord from system import database, spigotmc color_error = 0xfa5858 color_processing = 0x12a498 color_success = 0xdaa520 class Message: def __init__(self, message: discord.Message, has_premium: bool, load...
# config.py --- # # Description: # Author: Goncalo Pais # Date: 28 Jun 2019 # https://arxiv.org/abs/1904.01701 # # Instituto Superior Técnico (IST) # Code: import argparse arg_lists = [] parser = argparse.ArgumentParser() def add_argument_group(name): arg = parser.add_argument_group(name) arg_lists.append(...
from unittest import TestCase from analyzer import Pattern my_pattern = Pattern(name="my pattern", score=0.9, regex="[re]") my_pattern_dict = {"name": "my pattern", "regex": "[re]", "score": 0.9} class TestPattern(TestCase): def test_to_dict(self): expected = my_pattern_dict actual = my_pattern....
#!/usr/bin/env python # -*- coding: utf-8 -*- import scanpy as sc import matplotlib.pyplot as plt from matplotlib.path import Path as mpl_path import matplotlib.patches as patches import seaborn as sns import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D import numpy as np import pandas as pd ...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: my_dict = dict() temp = [] for i in range(len(s)): if s[i] not in temp: temp.append(s[i]) else: temp_str = ''.join(temp) # temp.clear() t...
# Copyright 2019-present, GraphQL Foundation # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from casing import snake from license import C_LICENSE_COMMENT class Printer(object): '''Printer for a simple list of types to be visited by t...
## An implementation of a Parallel Oblivious Unpredictable Function (POUF) # Stanislaw Jarecki, Xiaomin Liu: Fast Secure Computation of Set Intersection. # Published in SCN 2010: 418-435 from petlib.ec import EcGroup import pytest def POUF_setup(nid=713): """Parameters for the group""" G = EcGroup(nid) ...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants_test.pants_run_integration_test import PantsRunIntegrationTest class TestScalaLibraryIntegrationTest(PantsRunIntegrationTest): def test_bundle(self): pants_run = self.ru...
import io, gzip, boto3 from urllib.parse import urlparse def stream(url): s3 = boto3.resource('s3') _, bucket_name, key = urlparse(url).path.split('/', 2) obj = s3.Object( bucket_name=bucket_name, key=key ) buffer = io.BytesIO(obj.get()["Body"].read()) if key.endswith('.gz'): ...
""" Configures access to BingAds API and where to store results """ def data_dir() -> str: """The directory where result data is written to""" return '/tmp/bingads/' def first_date() -> str: """The first day from which on data will be downloaded""" return '2015-01-01' def developer_token() -> str:...
from ..requestsender import Wrapper class Stickers(object): __slots__ = ['fosscord', 's', 'edited_s', 'main_url', 'log'] def __init__(self, fosscord, s, main_url, log): #s is the requests session object self.fosscord = fosscord self.main_url = main_url+'/' if not main_url.endswith('/') else main_url self.s = s...
import logger import os class Trial: def __init__(self, name="Default_Trial", trial=["tailSetAngle(50, 1)", "tailSetAngle(20, 1.5)", "tailSetAngle(50, 2)", "tailSetAngle(20, 2.5)", "tailSetAngle(50, 3)", "tailSetAngle(20, 3.5)", "tailSetAngle(50, 4)", "tailSetAngle(20, 4.5)", "tailSetAngle(50, 5)", "tailSetAngle...
""" categories: Types,str description: UnicodeDecodeError not raised when expected cause: Unknown workaround: Unknown """ try: print(repr(str(b"\xa1\x80", 'utf8'))) print('Should not get here') except UnicodeDecodeError: print('UnicodeDecodeError')
# -*- coding: utf-8 -*- from entityClasses import Message, Action, ActionType from dbWrapper import RobertLogMSSQL from cn_utility import num_cn2digital, extract_cn_time import re import datetime import config import urllib import config import cn_utility import warning class ActionCenter: #SQL rlSQL = Robert...
from collections import Counter inputs = [] with open('day01.input') as f: inputs = [int(x) for x in f.readlines()] def most_common(xs): return Counter(xs).most_common(1)[0][0] def part1(ns): return most_common([n * (2020-n) for n in ns]) def part2(ns): return most_common([a*b*c for a in ns for b in ns for c i...
# -*- coding: utf-8 -*- """ Module to train the GNN. """ # Python Standard import logging # External dependencies import numpy as np import torch from sklearn.metrics import roc_auc_score # Internals from .symbols import DEVICE def train(model, dataset, n_epoch, learning_rate): """ Training function for a...
from django.test import TestCase from survey.models import SurveyOrderModel class SurveyOrderTest(TestCase): def setUp(self): SurveyOrderModel.objects.create( customer_faktura_id=1234, ) def test_blank_survey_created(self): obj = SurveyOrderModel.objects.get(customer_fakt...
#!/usr/bin/env python # 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, software...
# -*- coding: utf-8 -*- """ Code is generated by ucloud-model, DO NOT EDIT IT. """ import pytest import logging from ucloud.core import exc from ucloud.testing import env, funcs, op, utest logger = logging.getLogger(__name__) scenario = utest.Scenario(687) @pytest.mark.skipif(env.is_ut(), reason=env.get_skip_reason...
# generated by datamodel-codegen: # filename: openapi.yaml # timestamp: 2021-12-31T02:51:28+00:00 from __future__ import annotations from datetime import datetime from enum import Enum from typing import Annotated, Any, List, Optional from pydantic import BaseModel, Extra, Field class ResourceNotFoundExceptio...
# Copyright 2010 Google Inc. # # 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, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEbppDetectReportQueryResponse(AlipayResponse): def __init__(self): super(AlipayEbppDetectReportQueryResponse, self).__init__() self._audit_done = None s...
MutableSet = None try: from collections import MutableSet except ImportError: # Python 2.4 pass from theano.compat.python2x import OrderedDict import types def check_deterministic(iterable): # Most places where OrderedSet is used, theano interprets any exception # whatsoever as a problem that an o...
# -*- coding: utf-8 -*- """ Created on Wed Aug 12 18:24:12 2020 @author: omar.elfarouk """ import pandas import numpy import seaborn import scipy import matplotlib.pyplot as plt data = pandas.read_csv('gapminder.csv', low_memory=False) #setting variables you will be working with to numeric data[...
"""Tests for the classifiers of p1-FP.""" import pytest import numpy as np from lab.classifiers.p1fp import KerasP1FPClassifierC try: from lab.classifiers.p1fp import P1FPClassifierC except ImportError: USE_TFLEARN = False else: USE_TFLEARN = True if USE_TFLEARN: @pytest.mark.slow def test_p1fpcl...
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import uuid from unittest.mock import MagicMock import pytest import salt import saltext.vmware.modules.esxi as esxi_mod import saltext.vmware.states.esxi as esxi @pytest.fixture def dry_run(): setattr(esxi, "__opts__", {"test": True}) yield...
from unittest import TestCase from neo.Prompt.InputParser import InputParser class TestInputParser(TestCase): input_parser = InputParser() def test_simple_whitespace_separation(self): command, arguments = self.input_parser.parse_input("this is a simple test") self.assertEqual(command, "this")...
# Generated by Django 2.1.1 on 2018-09-19 19:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resume', '0001_initial'), ] operations = [ migrations.AddField( model_name='userprofile', name='alt_phone', ...
# # PySNMP MIB module TIMETRA-SAS-IEEE8021-CFM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-SAS-IEEE8021-CFM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:14:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
from minerva.proxy.checker import Checker from minerva.proxy.scraper import Scraper
import komand from .schema import RetrieveInput, RetrieveOutput, Component # Custom imports below class Retrieve(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='retrieve', description=Component.DESCRIPTION, input=RetrieveInpu...
from __future__ import print_function import ping import socket class Traceroute: def __init__(self, dest_addr, timeout=2, max_ttl=30, counts=4): self.ping = ping.Ping() self.dest_addr = dest_addr self.timeout = timeout self.max_ttl = max_ttl self.counts = counts se...
"""fix affaire abandon default value Revision ID: 5a8069c68433 Revises: ee79f1259c77 Create Date: 2021-09-06 16:28:58.437853 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5a8069c68433' down_revision = 'ee79f1259c77' branch_labels = None depends_on = None de...
SCHEMA_VERSION = "0.1" # The key to store / obtain cluster metadata. CLUSTER_METADATA_KEY = b"CLUSTER_METADATA" # The name of a json file where usage stats will be written. USAGE_STATS_FILE = "usage_stats.json" USAGE_STATS_HEADS_UP_MESSAGE = ( "Usage stats collection will be enabled by default in the next releas...
# coding: utf-8 import marisa_trie import pickle import math #tf_trie = marisa_trie.Trie() #tf_trie.load('my_trie_copy.marisa') #data = open('tf_trie.txt', 'rb') data = open('tf_trie.txt', 'rb') tf_trie = pickle.load(data) isf_data = open('isf_trie.txt', 'rb') #isf_data = open('isf_trie.pickle', 'rb') isf_trie = pickl...
import time import os import youtube_dl import cheesepi as cp import Task logger = cp.config.get_logger(__name__) class Dash(Task.Task): # construct the process and perform pre-work def __init__(self, dao, spec): Task.Task.__init__(self, dao, spec) self.spec['taskname'] = "dash" if not 'source' in spec: ...
import logging import multiprocessing import time from rpi.logging.listener import LoggingListener from rpi.network.server import Server # from rpi.sensors.accelerometer import Accelerometer from rpi.sensors.accelerometer_i2c import Accelerometer from rpi.sensors.pressure import Pressure from rpi.sensors.thermometer i...
from collections import Counter, defaultdict import itertools import math as m test = """3,4,3,1,2""" def part1(data, daymax=80): for day in range(daymax): n = [] for i in range(len(data)): if data[i] == 0: data[i] = 6 n.append(8) else: ...
classTemplate = \ """/* * This file is generated. Please do not modify it manually. * If you want to update this file, run the generator again. * */ package {package}; {imports} public class Alias implements AliasInterface {{ @Override public Map<String, String> getFileMap() {{ return File....
import mailer as m import consoleLogger as cl import fileLogger as fl ''' Created by: Richard Payne Created on: 05/08/17 Desc: Takes string from connection and extracts username, password and IP address of the attempted login. ''' def format(ip, usr, pw): ip = ip usr = usr.rsp...
import logging from collections import OrderedDict, defaultdict from decimal import Decimal as D from django.conf import settings from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.db import models from django.utils import t...
import psutil from multiprocessing import Pool from tqdm import tqdm import numpy as np import xarray as xr def track_events(class_masks_xarray, minimum_time_length=5, tc_drop_threshold=250, ar_drop_threshold=250, future_lookup_range=1): """track AR and TC events across time ...
from typing import List import pydantic class EnvConstants(pydantic.BaseSettings): """Environment constants. Constants should be set in .env file with keys matching variable names at root of project. """ API_KEY_TABLE_NAME: str FIREHOSE_TABLE_NAME: str SENTRY_DSN: str SENTRY_ENVIR...
import distutils.spawn import os from pathlib import Path from pytest import fixture from pytest_ngrok.install import install_bin from pytest_ngrok.manager import NgrokContextManager try: from .django import * # noqa except ImportError: pass def pytest_addoption(parser): parser.addoption( '--ng...
#!/usr/bin/env python """ Make the lg1 file for GOES-R type resolution overlaid on TEMPO with GEOS-R parking spot """ import numpy as np from numpy import radians, degrees from math import radians, cos, sin, asin, sqrt, tan, atan from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import matplotlib.pyp...
my_grades = { "linguagens": 630, "humanas" : 660, "natureza" : 660, "matematica" : 830, "redacao" : 800 } matematica_aplicada = { "curso" : "Matemática Aplicada", "corte" : 720.96, "linguagens" : 3, "humanas" : 1, "natureza" : 4,...
def solveMeFirst(a,b): return a + b
powers = [31] channels = [26] sinks = [1] testbed = "fbk" start_epoch = 1 active_epochs = 200 full_epochs = 15 #num_senderss = [0,1,2,5,10,20] num_senderss = [1,20] period = 1 n_tx_s = 3 dur_s = 10 n_tx_t = 3 dur_t = 8 n_tx_a = 3 dur_a = 8 payload = 2 longskips = [0] n_emptys = [(2,2,4,6)] ccas = [(-15, 80)] n...
# -*- coding: utf-8 -*- """Top-level package for Python Business Objects import.""" __author__ = """Hugo van den Berg""" __email__ = '[email protected]' __version__ = '0.1.0'
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 15:55:15 2019 @author: tsd """ import torch from .tokenization_albert import AlbertTokenizer from .preprocessing_funcs import save_as_pickle, load_pickle from .ALBERT import AlbertForSequenceClassification import logging logging.basicConfig(format='%(asctime)s [%(leve...
#!/usr/bin/env python from __future__ import print_function import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class UMat(NewOpenCVTests): def test_umat_construct(self): data = np.random.random([512, 512]) # UMat constructors data_um = cv.UMat(data) # from ndarr...
""" Class Hierarchy G{classtree: BaseController} Package tree G{packagetree: controller} Import Graph G{importgraph: controller} """ from cluster_tool import KubernetesTool from controller_param import ControllerParam class BaseController: def __init__(self,controller_id,config_path): self.controller_id = ...
from ._node import Node __all__ = ['List'] class EmptyError(ValueError): """ Raised when a list is empty. """ class NotEmptyError(ValueError): """ Raised when a list not is empty. """ class List: """ Doubly linked list. >>> a = List.from_iterable([1, 2, 3]) >>> print(a) ...
# ===================================================================================== # Copyright (c) 2010-2012, G. Fiori, G. Iannaccone, University of Pisa # # This file is released under the BSD license. # See the file "license.txt" for information on usage and # redistribution of this file, and for a DISCLAI...
# Copyright (c) 2013, Frappe and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe OUTBOUND_SUFFIX = "Outbound" KARIGAR_SUFFIX = "Karigar" INBOUND_SUFFIX = "Inbound" SPACE = " " def execute(filters=None): columns, data = [], [] #items_code_sta...
def not_gate(bit): assert bit in (0, 1), "Only 0 or 1" if bit: return 0 return 1 def and_gate(bit1, bit2): assert bit1 in (0, 1) and bit2 in (0, 1), "Only 0 or 1" return bit1 * bit2 def or_gate(bit1, bit2): assert bit1 in (0, 1) and bit2 in (0, 1), "Only 0 or 1" if 1 in (bit1, bi...
"""Test module for the Templates plugin.""" import unittest import os import cProfile, pstats import test_project test_project.TEST_SETTINGS += """ from modelmanager.plugins import templates from modelmanager.plugins.templates import TemplatesDict as _TemplatesDict from modelmanager import utils @utils.propertyplugi...
# -*- coding: utf-8 -*- # Код основан на пакете esia-connector # https://github.com/eigenmethod/esia-connector # Лицензия: # https://github.com/eigenmethod/esia-connector/blob/master/LICENSE.txt # Copyright (c) 2015, Septem Capital import base64 import datetime import json import os import tempfile import pytz impo...
# 24 from math import factorial n = list(range(10)) f = [] left = 1000000 for i in range(9): if left % factorial(9 - i) == 0: f += [n.pop(int(left / factorial(9 - i)) - 1)] else: f += [n.pop(int(left / factorial(9 - i)))] left = left % factorial(9 - i) f += n print(f)
import argparse import cv2 import os import shutil import subprocess import sys def check_for_ffmpeg(): with open(os.devnull, 'w') as devnull: try: ret = subprocess.call(['ffmpeg', '-version'], stdout=devnull) except OSError: ret = 1 if ret != 0: print ...
""" remote_method decorator """ from zorp.registry import registry def func_name(func): """ Return func's fully-qualified name """ if hasattr(func, "__module__"): return "{}.{}".format(func.__module__, func.__name__) return func.__name__ def remote_method(name=None, use_registry=registr...
import redis from django.conf import settings from .models import Product # Connect to redis conn = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) class Recommend(object): def get_product_id(self, id): return f'product:{id...
#-*-coding:utf-8-*- import librosa import numpy as np import random import os , time import soundfile from multiprocessing import Pool sample_rate = 16000 pitch_shift1, pitch_shift2 = 0.01 , 5.0 time_stretch1, time_stretch2 = 0.05, 0.25 augmentation_num = 10 def audio_augmentation(wav_file): print("original wa...
#!/usr/bin/env python3 """ Copyright 2018 Twitter, Inc. Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 """ """ This script can be used to add license headers to all the source files of a project. It is designed to be safe, so do not worry and try it out! Works with language...
from .models import PREVIEW_FLAG class ContentModelAdminMixin(object): """Enables staff preview of non-live objects, in combination with ContentModelQuerySet.live(request). Note the view must pass a request to this method or the preview won't work, and the mixin needs to come before admin.Mo...
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGroupBox, QPushButton, QComboBox, QSizePolicy class ImageControlsWidget(QWidget): def __init__(self): super().__init__() self.classes = [] self.init_ui() def init_ui(self): prevButton = QPushButton("Previous") nextBu...
import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True, help= 'Path to the image') args = vars(ap.parse_args()) # load the image, grab its dimensions and show it image = cv2.imread(args['image']) (h, w) = image.s...
import atexit from math import sin, cos from numpy import array from pycuda import driver from pycuda import gpuarray from _axpy import daxpy n = 10000 a = 3.4 def detach(context): context.pop() context.detach() # initialise CUDA driver.init() device = driver.Device(0) context = device.make_context(flags=d...
""" Enum of available ONS indexes """ from enum import Enum from dp_conceptual_search.config import CONFIG class Index(Enum): ONS = CONFIG.SEARCH.search_index DEPARTMENTS = CONFIG.SEARCH.departments_search_index
from hlwtadmin.models import Artist, GigFinderUrl, GigFinder, ConcertAnnouncement, Venue, Location, Organisation, Country, Concert, RelationConcertConcert, RelationConcertOrganisation, RelationConcertArtist, Location, ConcertannouncementToConcert from django.core.management.base import BaseCommand, CommandError from ...
import logging import os from flask import Flask, jsonify, redirect, request from flask_cors import CORS from flasgger import Swagger from ensembl.production.metadata.config import MetadataConfig from ensembl.production.core.models.hive import HiveInstance from ensembl.production.core.exceptions import HTTPRequestErro...
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
# -*- encoding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 8 _modified_time = 1434060690.119963 _enable_loop = True _template_filename = '/home/cairisuser/CAIRIS-web/cairis/cairis/templates/index.mako' _template_uri...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2019 Huawei # GNU General Public License v3.0+ (see COPYING or # https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type #################################################################...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='ImportedObjects'...