content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/python
import aud, sys, time, multiprocessing
device = aud.Device()
hrtf = aud.HRTF().loadLeftHrtfSet(".wav", sys.argv[2])
threadPool = aud.ThreadPool(multiprocessing.cpu_count())
source = aud.Source(0, 0, 0)
sound = aud.Sound.file(sys.argv[1]).rechannel(1).binaural(hrtf, source, threadPool)
handle = device.... | python |
# coding: utf-8
# flake8: noqa
"""
Velo Payments APIs
## Terms and Definitions Throughout this document and the Velo platform the following terms are used: * **Payor.** An entity (typically a corporation) which wishes to pay funds to one or more payees via a payout. * **Payee.** The recipient of funds paid ... | python |
from data.mag.build_docs_from_sqlite import generate_papers, UPDATE_GENERATORS, strip_and_dump_from_gen
from solr.instances import get_session
from data import upload_batches_unparsed
from solr.session import SolrSession
from solr.configsets import get_config
from multiprocessing import Pool, cpu_count
import itertools... | python |
"""
Module to log on screen
====================================
"""
# ============================================================================
# STANDARD IMPORTS
# ============================================================================
import click
from functools import partial
from click.termui import s... | python |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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
#
# ... | python |
#!/usr/bin/env python3
import subprocess
import os
import glob
import sys
import time
import argparse
def merge(infile, outfile, id_name_map):
merge_dict = {}
with open(infile, 'r') as f:
content = ""
name = ""
for line in f:
if line[0] == ">":
name = line[1:].strip()
if name n... | python |
#---------------------------------------
# Import Libraries
#---------------------------------------
import sys
import json
import codecs
import os
#---------------------------------------
# [Required] Script Information
#---------------------------------------
ScriptName = "Queue Display"
Website = "twitch.tv/enc... | python |
"""Implementation of the StarBound block file v2/3 storage"""
import logging
import struct
from starfuse.fs.mapped_file import MappedFile
log = logging.getLogger(__name__)
class InvalidMagic(Exception):
"""A block file has an invalid magic string"""
def __init__(self, path):
super(InvalidMagic, sel... | python |
import pandas as pd
import numpy as np
def load_file(filename: str):
"""Load the .xls file and return as a dataframe object."""
df = pd.read_csv(filename, delimiter='\t')
return df
data = load_file('outputs.xls')
print(data.info())
| python |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import csv
import sys
import json
import pickle
import logging
from copy import deepcopy
from collections import Counter
from itertools import groupby, chain
from indra.statements import Agent
from indra.da... | python |
__author__ = 'marcusmorgenstern'
__mail__ = ''
import copy
import os
import unittest
from os.path import join
import numpy as np
from pyfluka.base import InvalidInputError
from pyfluka.reader.UsrbinReader import UsrbinReader as UR
from pyfluka.utils import PhysicsQuantities as PQ
_basedir = os.path.dirname(__file__)
... | python |
# @lc app=leetcode id=211 lang=python3
#
# [211] Design Add and Search Words Data Structure
#
# https://leetcode.com/problems/design-add-and-search-words-data-structure/description/
#
# algorithms
# Medium (41.04%)
# Likes: 3106
# Dislikes: 130
# Total Accepted: 293.8K
# Total Submissions: 712.7K
# Testcase Examp... | python |
from django.shortcuts import render
from django.views.generic import TemplateView
from booking.models import Booking
from userprofile.models import userProfile
class IndexPageView(TemplateView):
template_name = 'main/index.html'
class ChangeLanguageView(TemplateView):
template_name = 'main/change_language.... | python |
from sqlalchemy import (
create_engine, Column, MetaData,
Integer, String, Numeric, DateTime)
from sqlalchemy.orm import class_mapper
from .common import (
generate_sqla_connection_uri,
_insert_entries_from_log_file,
_import_logs_from_folder)
from sqlalchemy.orm import scoped_session, sessionmaker
f... | python |
from __future__ import print_function, division, absolute_import
import numpy as np
import networkx as nx
from visvis import ssdf
from stentseg.utils.new_pointset import PointSet
from stentseg.stentdirect.stentgraph import (StentGraph, check_path_integrity,
_get_pairs_of_neighbours, add_nodes_at_crossings,
... | python |
from pyspark import SparkContext
from pyspark.sql.functions import count, lit, col, udf, collect_list, explode, sqrt, mean
from pyspark.sql.types import IntegerType, StringType, MapType, ArrayType, BooleanType, FloatType
from pyspark.sql import SQLContext, HiveContext
import sys
def filter_slot_id(df, slot_ids=[]):
... | python |
# -*- coding: utf-8 -*-
# Copyright 2015 www.suishouguan.com
#
# Licensed under the Private License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE
#
# Unless ... | python |
"""
These are utilities for the `/bin` scripts, not for the `cibuildwheel` program.
"""
from io import StringIO
from typing import Dict, List
from .typing import Protocol
__all__ = ("Printable", "dump_python_configurations")
class Printable(Protocol):
def __str__(self) -> str:
...
def dump_python_con... | python |
# -*- coding: utf-8 -*-
# global
import io
import sys
import json
import logging
import pandas as pd
# core
import core
import core.utils
import core.indexer
from core.DocVocabulary import DocVocabulary
from core.TermVocabulary import TermVocabulary
from core.features import Features
from core.msg import TwitterMessa... | python |
class Dinosaur:
def __init__(self, name, attack_power):
self.name = name
self.attack_power = int(attack_power)
self.health = 50
self.energy = 100
self.att_list = ["Tail Whip", "Body Slam", "Stomp", "Hyper Beam"]
self.att = "error"
def attack(self, robot):
... | python |
#!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.data import kb
from lib.request.connect import Connect as Request
def getPageTemplate(payload, place):
retVal = (kb.originalPage, kb.errorIsNone)
if pa... | python |
# def encode_as_bytes(input_file_path: str, output_gif_path: str):
# """
# The practical encoder with optimized GIF assembler and multiprocessing acceleration.
#
# :param input_file_path: input file path
# :param output_gif_path: output gif file path
# :param chunk_string_length: the length of base6... | python |
# Version: 2020.02.21
#
# MIT License
#
# Copyright (c) 2018 Jiankang Deng and Jia Guo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitatio... | python |
n= str(input("digite um valor ")).upper().strip()
d=n.split()
j= ''.join(d)
inver= ''
for i in range(len(j)-1,-1,-1):
inver+=j[i]
if n==inver:
print("o valor é um palindromo")
else:
print("o valor não é um palindromo")
| python |
import itertools
import random
S = " "
def main():
# init
gophers_count = 100
windmills_count = 18
factors = [17, 13, 11, 7, 5, 3, 2]
seed = 1951
a, b, c = [], [], []
random.seed(seed)
# generate input data for each night
for f in factors:
windmills = [f] * windmills_cou... | python |
from tensorflow.keras.layers import LSTM, Dense, TimeDistributed, Masking, BatchNormalization, Dropout, Input, \
Bidirectional, ConvLSTM2D, Attention
from tensorflow.keras.models import Model
from lsct.models.cnn_1d import CNN1D
from cnn_lstm.attention_with_context import Attention
def create_cnn_lstm_model(clip... | python |
"""CFNgin entrypoint."""
import logging
import os
import re
import sys
from yaml.constructor import ConstructorError
from runway._logging import PrefixAdaptor
from runway.util import MutableMap, SafeHaven, cached_property
from .actions import build, destroy, diff
from .config import render_parse_load as load_config
... | python |
x3 = ('foo'
('bar'<caret> | python |
import numpy as np
from pymgt import *
from pymgt.metrics import *
from pymgt.ppmt_utils import friedman_index
def test_():
ndata = 1000
np.random.seed(1)
x = np.random.uniform(0.0, 1.0, size=ndata)
metrics = [
("friedman", FRIEDMAN_METRIC, False),
("kstest", KS_METRIC, False),
... | python |
# -*- coding: utf-8 -*-
#
# Copyright (c) {% now 'utc', '%Y' %}, {{ cookiecutter.author }}
# All rights reserved.
#
import unittest
from cnct import ConnectClient
from connect_processor.app.cancel import Cancel
from unittest.mock import patch, MagicMock
from tests.test_util import TestUtils
client = ConnectClient('Key... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains functions used to convert osm data to json and save to MongoDB.
"""
import xml.etree.cElementTree as ET
import json
#some post on stackoverflow
def elementtree_to_dict(element):
""" Function used to recursively convert a eleme... | python |
class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
productions = []
n = len(nums)
if n == 0:
return None
# def recursiveProductExceptSelf(idx=0, previous_value=1):
# nonlo... | python |
# Generated by Django 3.0.4 on 2020-03-22 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0006_auto_20200322_1440'),
]
operations = [
migrations.AddField(
model_name='violationreport',
name='cont... | python |
# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
import numpy as np
class CifarGenerator:
"""
Generator class responsible for supplying data to the model.
Attributes
----------
x: np ndarray
array of images
y: np ndarray
array of class labels
... | python |
"""Functions to assist with remote logging of InVEST usage."""
import logging
import urllib
import urllib2
import json
import Pyro4
LOGGER = logging.getLogger('natcap.invest.remote_logging')
Pyro4.config.SERIALIZER = 'marshal' # lets us pass null bytes in strings
_ENDPOINTS_INDEX_URL = (
'http://data.naturalca... | python |
from dolfin.fem.problem import LinearVariationalProblem
from dolfin.cpp.fem import LinearVariationalSolver
from fenics_utils.formulation.cfd import IncompressibleNsIpcs
from fenics_utils.formulation.cfd import AdvectionDiffusionScalar
from fenics_utils.solvers.linear import LinearSolver
class AdvectionDiffusionScala... | python |
from __future__ import print_function
import boto3
import logging
import time
current_session = boto3.session.Session()
current_region = current_session.region_name
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#create a client connection to ec2
ec2_client = boto3.client('ec2', current_region)
... | python |
"""!
@brief Phase oscillatory network for patten recognition based on modified Kuramoto model.
@details Implementation based on paper @cite article::nnet::syncpr::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import math
import cmath
import numpy
from pyclustering.... | python |
from api.libs.base import CoreView
from cmdb.models import MachineRoom, DataCenter
from account.models import UserProfile
from django.db.utils import IntegrityError
class MachineRoomView(CoreView):
"""
机房视图类
"""
login_required_action = ["get_list", "post_create", "post_delete", "post_change"]
supe... | python |
#!"D:\STORE\0-Admin\Desktop\Chatbot-Osiris bkp\python.exe"
import sys
import subprocess
subprocess.call("start cmd /k echo "+sys.argv[1], shell=True) | python |
from django import template
from django.template.loader import get_template
register = template.Library()
@register.filter(name='is_deploma')
def is_deploma(value):
return value['year'] == '2' and value['course'] == 'BTech'
@register.filter(name='is_first_year')
def is_first_year(value):
return value['year']... | python |
import discord
from discord.ext import commands
import sqlite3
from helper import utils
class SettingsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(help= 'Used to set the prefix of the bot in this server, use default to default to the global prefix', usage='pref... | python |
# coding: utf-8
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import networkx as nx
import itertools
import pandas
from networkx.readwrite import json_graph
from scipy import spatial
import re
__author__ = "Adrien Guille, Pavel Soriano"
__email__ = "adri... | python |
import RPi.GPIO as GPIO
import time
import threading
import os
import sys
# constants
SLOWFLASHTIMES = [2,2]
FASTFLASHTIMES = [0.5,0.5]
# class for managing LED
class LEDControl():
class LEDStates():
#states of LED
OFF = 0
ON = 1
FLASH = 2
def __init__(self, gpioPin):
... | python |
# REQUIRES: bindings_python
# RUN: %PYTHON% %s | FileCheck %s
import circt
from circt.dialects import rtl
from mlir.ir import *
from mlir.dialects import builtin
with Context() as ctx, Location.unknown():
circt.register_dialects(ctx)
i32 = IntegerType.get_signless(32)
m = builtin.ModuleOp()
with In... | python |
#!/usr/bin/env pytest
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read functionality for FITS driver.
# Author: Even Rouault <even dot rouault @ mines-paris dot org>
#
########################################################... | python |
from xml.dom.minidom import Document
from django.shortcuts import redirect, render
def add_file(request):
if request.method == 'POST':
updated_file = request.FILES['document']
print(updated_file.name)
print(updated_file.size)
return render(request, 'base/add_file.html',{}) | python |
import os
import json
import importlib
from typing import Callable, TypeVar
AnyFunction = Callable
Handler = TypeVar('Handler')
def getClass(modulePath: str, className: str):
mod = importlib.import_module(modulePath)
return getattr(mod, className)
def getAction(fileName: str, actionName: str) -> Callable:... | python |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2021, A.A Suvorov
# All rights reserved.
# --------------------------------------------------------
"""Tests prototype.py"""
from patt... | python |
import numpy as np
from scipy.stats import iqr
from ..config import MAX_VAL_AFTER_NORMALIZATION
from ..utils.dataUtils import morphDilation, gaussianFilter, radial_profile, applyRelativeThr, getCoordsWithinSphere
from ..utils.genericException import GenericError
DEFAULT_PERCENTIL = 95
DEFAULT_BINARY_MASK_THR= 0.01
d... | python |
import pytest
import requests
from log_config import log_, pformat
from core import config
from tests.utils.utils import get_server_api, client
### - - - - - - - - - - - - - - - - - - - - - - - ###
### LOGINS
### - - - - - - - - - - - - - - - - - - - - - - - ###
def client_anonymous_login(
as_test = True... | python |
import glob
import os
import re
class JasmineTest:
def __init__(self, test_name, test_class_name, test_path, included_tags: list, excluded_tags: list):
self.test_name = test_name
self.test_class_name = test_class_name
self.test_path = test_path
self.included_tags = included_tags
... | python |
STATS = []
num_timeouts = 15
num_timeouts = 40
num_problems = 55
| python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Configuracion Pyro4
DATABASE = 'ws.db'
OBJETO_PYRO = 'servidor1.configura'
DIRECCION_PYRO = '192.168.1.115' # en nuestro caso la direccion del objeto y del servidor de nombrado será el mismo ya que estan en la misma maquina
DIRECCION_PYRO_LOCAL = '192.168.1.115'
KEY = ... | python |
from django.contrib import admin
from django.contrib.admin.utils import reverse_field_path
from django.db.models import Max, Min
from django.db.models.fields import DecimalField, FloatField, IntegerField
from .forms import RangeNumericForm, SingleNumericForm, SliderNumericForm
class NumericFilterModelAdmin(admin.Mod... | python |
# -*- coding: utf-8 -*-
# @Author: Liu Shaoweihua
# @Date: 2019-11-18
# Copyright 2018 The Google AI Language Team Authors.
#
# 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://w... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Busana Apparel Group. All rights reserved.
#
# This product and it's source code is protected by patents, copyright laws and
# international copyright treaties, as well as other intellectual property
# laws and treaties. The product is licensed, not s... | python |
import cv2
import os
import glob
from matplotlib import pyplot as plt
import numpy as np
def readImages(path):
img_array = []
imgc = []
names = []
for filename in glob.glob(path):
names.append(filename)
names.sort()
for filename in names:
img = cv2.imread(filen... | python |
#!/usr/bin/env python
from __future__ import absolute_import
import sys
import argparse
import symstore
class CompressionNotSupported(Exception):
pass
def parse_args():
parser = argparse.ArgumentParser(
description="publish windows debugging files")
parser.add_argument("-d", "--delete",
... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | python |
__version__ = "v0.1.0" | python |
# flake8: noqa
from .load_catalog import load_catalog
| python |
import ctypes
class MemoryBuffer:
def __init__(self, ptr):
self.start_addr = ptr
self.position = ptr
def tell(self):
return self.position
def read(self, count):
if count == 0:
return b''
if count < 0:
raise Exception('Cant read negative num... | python |
# coding: utf-8
from graph import UndirectedGraph, Vertex
from reporter import Reporter
from typing import Callable, List, Set
import random
PivotChoice = Callable[[UndirectedGraph, Set[Vertex]], Vertex]
def visit(graph: UndirectedGraph, reporter: Reporter, pivot_choice_X: bool,
candidates: Set[Vertex], ... | python |
class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
lls = {}
dls = []
for log in logs:
_, v = log.split(" ", 1)
if v.split(" ", 1)[0].isalpha():
lls[log] = v
... | python |
from flask import render_template,request,redirect,url_for, abort
from . import main
from flask_login import login_required,current_user
from .forms import PitchesForm,CommentsForm,UpdateProfile
from ..models import Pitches,Comments,User
from .. import photos, db
from datetime import datetime
# from ..requests import ... | python |
from hashlib import sha256
import json
from typing import Protocol
from flask import *
from flask_cors import CORS
from Crypto.Cipher import AES
from script import decrypt, encrypt
from get_data import get_all_data
from flask_talisman import Talisman
from addData import readJson,writeJson
import json
from ml import pre... | python |
import pygame
import utils
import constants
import os, sys
# -----------------------------------------------------------
# class Environment
# -----------------------------------------------------------
class Environment:
def __init__(self, zone_name, map_name):
if zone_name is None o... | python |
# Generated by Django 3.1.8 on 2021-06-24 16:23
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | python |
import pathlib
import pyopenephys
import numpy as np
"""
The Open Ephys Record Node saves Neuropixels data in binary format according to the following the directory structure:
(https://open-ephys.github.io/gui-docs/User-Manual/Recording-data/Binary-format.html)
Record Node 102
-- experiment1 (equivalent to a Session... | python |
import yaml
import xdg
from dataclasses import dataclass, field
from typing import Dict
from pathlib import Path
@dataclass
class Configuration:
path: str = field(default=xdg.XDG_DATA_HOME / "quest/tasks.yaml")
trello: Dict = field(default_factory=dict)
taskfile: Path = field(default=xdg.XDG_DATA_HOME / "... | python |
import os
def modifyFile(_f):
_new_f = _f.replace(' - 副本.js', '.ts')
os.rename(_f, _new_f)
def getFile(_d):
dirs = os.listdir(_d)
for k in dirs:
fpth = _d + "/" + k
f = os.path.isfile(fpth)
if f == False:
getFile(fpth)
else:
i =... | python |
from time import sleep
import unittest,random,sys
sys.path.append('./models')
sys.path.append('./page_obj')
from models import function,myunit
from page_obj.loginPage import Login
class LoginTest(myunit.MyTest):
'账户登录测试'
def user_login_verify(self,username='',password=''):
Login(self.driver).user_log... | python |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.testing.unit_test import unit_test
from bes.version.software_version import software_version as VC
class test_software_version(unit_test):
def test_compare(self):
self.assertEqual( -1, VC.compare('1.2.3', '1.2.4... | python |
# Generated by Django 3.1.6 on 2021-05-01 19:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ecom', '0007_contact'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'verbose_name_plural': 'Cat... | python |
import sys
import math
import numpy as np
import pandas as pd
def topsis_fun(file,wght,impact):
try:
mat=pd.read_csv(file)
except FileNotFoundError:
raise Exception("File does not exist")
#print(mat)
row_count=mat.shape[0]
col_count=mat.shape[1]
if(len... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 20:19:16 2020
@author: taotao
"""
import check_db
def status_check():
print('进入计算检测')
return
def calculate(message,trigger,item_price):#识别并计算
if(trigger == 1):
people = message[-1].split("@")
people = people[1:]
print('people_list:',p... | python |
# Generated by Django 2.1.5 on 2019-03-24 01:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0007_auto_20190324_0118'),
]
operations = [
migrations.RemoveField(
model_name='serveruser',
name='password',
... | python |
import math
import bcolors
class Plot(object):
def __init__(self, x_min, x_max, x_size, y_min, y_max, y_size, t_min, t_max, t_size):
self.x_min = x_min
self.x_max = x_max
self.x_size = x_size
self.y_min = y_min
self.y_max = y_max
self.y_size = y_size
self.t_min = t_min
self.t_max = t_max
self.t_siz... | python |
# Copyright 2013-2014 The rust-url developers.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except ac... | python |
# pyOCD debugger
# Copyright (c) 2013-2019 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# 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... | python |
from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed
from rest_framework_extensions.mixins import NestedViewSetMixin
from resources_portal.models import Material
from resources_portal.serializers import MaterialRelationSerializer
class OrganizationMaterialViewSet(NestedViewSetM... | python |
"""
Usage:
source env.sh ; python storage.py create_blob_container openflights-raw
source env.sh ; python storage.py create_blob_container openflights-adf
source env.sh ; python storage.py create_blob_container test
source env.sh ; python storage.py delete_blob_container openflights-raw
source env.s... | python |
"""Command-line interface for Acton."""
import logging
import struct
import sys
from typing import BinaryIO, Iterable, List
import acton.acton
import acton.predictors
import acton.proto.wrappers
import acton.recommenders
import click
def read_bytes_from_buffer(n: int, buffer: BinaryIO) -> bytes:
"""Reads n byte... | python |
import logging
def debug(*args, **kw):
logging.basicConfig(level=logging.ERROR, format="%(message)s")
logger = logging.getLogger(__name__)
logger.debug(*args, **kw)
| python |
import os
from os import path
from IPython import embed
import click
import pandas as pd
import numpy as np
from root2csv import converter
from csv2hdf5 import glob_and_check
from remove_events import get_run
from melibea import process_melibea
def check_globs(glob1, glob2):
if isinstance(glob1, str):
fna... | python |
# -*- coding: utf-8 -*-
__all__ = ['Sample', 'reserved_keys']
reserved_keys = ['image_bytes', 'image_type', 'image_path', 'image', 'bboxes', 'bbox_labels']
class Sample(dict):
"""
Sample class is a subclass of dict, storing information of a single sample
The following keys are reserved:
'image_bytes... | python |
# -*- coding: utf-8 -*-
import json
class User(object):
def __init__(self, user_id, user_name, user_surname, email):
self.user_id = user_id
self.user_name = user_name
self.user_surname = user_surname
self.email = email
# self.userLevel = userLevel
# self.userTitle ... | python |
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
from qgis.core import (
QgsApplication,
QgsDataSourceUri,
QgsCategorizedSymbolRenderer,
QgsClassificationRange,
QgsPointXY,
QgsProject,
QgsExpression,
QgsField,
QgsFields,
QgsFeature,
QgsFeatu... | python |
"""Поле для ссылки на сертификат
Revision ID: 7f6d52e2a594
Revises: 4028ddc57d5b
Create Date: 2021-01-17 16:47:35.551727
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7f6d52e2a594'
down_revision = '4028ddc57d5b'
branch_labels = None
depends_on = None
def u... | python |
"""
This class defines the Attention Layer to use when training the model with the attention mechanism.
Code readapted (under the courtesy of the author) from:
https://github.com/lukemelas/Machine-Translation
"""
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, b... | python |
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | python |
import numpy as np
from scipy.fftpack import dct
def cutSample(data):
if len(np.shape(data))==2:
data=data[:,0]
fadeamount = 300
maxindex = np.argmax(data > 0.01)
startpos = 1000
if len(data) > 44100:
if maxindex > 44100:
if len(data) > maxindex + (44100):
... | python |
import json
from dagster_slack import slack_resource
from mock import patch
from dagster import ModeDefinition, execute_solid, solid
@patch("slack_sdk.WebClient.api_call")
def test_slack_resource(mock_api_call):
@solid(required_resource_keys={"slack"})
def slack_solid(context):
assert context.resour... | python |
import base64, httplib, json
def googlecloud_tagimage(filename):
with open(filename, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read())
endpoint = '/v1/images:annotate?key=ADD_YOUR_KEY_HERE'
request_body = {
'requests':[
{
'image':{
... | python |
import sys
numArray = sys.argv
uniques = []
for num in numArray:
if num not in uniques:
uniques.append(num)
print("Unique Numbers are ", end=':')
for num in uniques:
print(num, sep=",")
| python |
# -*- coding: utf-8 -*-
import unittest
from includes import *
from common import getConnectionByEnv, waitForIndex, sortedResults, toSortedFlatList
from time import sleep
from RLTest import Env
def testSyntax1(env):
conn = getConnectionByEnv(env)
env.expect('ft.create', 'idx',
'ONfoo*',
... | python |
def python_vignette():
from tests import pyunit_utils
story1 = [pyunit_utils.locate("python/ipython_dataprep_input.py")]
story2 = [pyunit_utils.locate("python/ipython_machinelearning_input.py")]
approved_py_code_examples = story1+story2
pybooklet_utils.check_code_examples_in_dir(approved_py_code_e... | python |
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
import random
import pyperclip
import json
def genrate_password():
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'A', 'B',... | python |
from sys import path
from os.path import dirname as dir
path.append(dir(path[0]))
__package__ = "model"
from model import inference
from datetime import datetime
INFERENCE_TYPE = 'local' # local' | 'cmle'
instances = [
{
'is_male': 'True',
'mother_age': 26.0,
'mother_ra... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.