content stringlengths 5 1.05M |
|---|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import imp
import os
import re
import functools
import sys
import socket
import time
import types
import unittest
import... |
# coding: utf-8
import sys
IS_WINDOWS = (sys.platform == "win32")
|
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from apikey import apikey
import time
class YoutubeBot:
flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', 'https://www.googleapis.com/auth/youtube.force-ssl')
credentials = flow.run_console()... |
import os
for filename in os.listdir('.'):
if filename.endswith('.kml'):
os.rename(filename, filename[:-3]+'xml')
|
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def test():
return {"teste": "testado!"} |
import json
import glob
import re
# onetime script to convert the data/people/*.txt files to data/people/*.json files
for txt_file in glob.glob('data/people/*.txt'):
person = {}
with open(txt_file, encoding="utf-8") as fh:
for line in fh:
line = line.rstrip('\n')
if re.search(r'\A... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
__author__ = 'Kalyan'
from placeholders import *
notes = '''
Tuples are yet another sequence type along the lines of strings and lists with
its own characteristics.
'''
def test_tuple_type():
test_tuple = (1,2) # note the syntax
assert 'tuple' == type(test_tuple).__name__
def test_tuple_lengt... |
from __future__ import annotations
import os
from getpass import getpass
from time import sleep
import pandas as pd
from notion_client import Client as NotionClient
def get_notion_token() -> str:
"""Gets a Notion API token.
Either from the NOTION_TOKEN environment variable or interactively.
Returns
... |
# Generated by Django 3.1.13 on 2021-07-21 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20210721_1547'),
]
operations = [
migrations.AlterField(
model_name='college',
name='name',
... |
import uvicorn
from fastapi import FastAPI
from dotenv import load_dotenv
from layer_view import view
load_dotenv()
app = FastAPI()
app.include_router(view.router)
if __name__ == "__main__":
uvicorn.run(
"app:app", host="0.0.0.0", port=5111, reload=True
) |
import argparse
import os
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
from data.dataset import OmniglotReactionTimeDataset
from helpers.statistical_functions import calculate_base_statistics, display_base_stat... |
#!/usr/bin/env python
#
# Copyright 2012 Jim Lawton. 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 requir... |
import os
import imutils
import pickle
import time
import cv2
import threading
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import json
import datetime
import requests
from faced import FaceDetector
from faced.utils import annotate_image
from config_reader import read_config
ZM_URL = 'http://18.179... |
import cv2
from PIL import Image
import numpy as np
cam = cv2.VideoCapture(0)
## Keys ##
class Keys(object):
overall = lambda x: (int(x[0]) + int(x[1]) + int(x[2]))
red = lambda x: (int(x[0]))
green = lambda x: (int(x[1]))
blue = lambda x: (int(x[2]))
avg = lambda x: (int(x[0]) + int(x[1]) + int... |
# dictionary
d1 = {"tom":30, "bobe":3}
print("d1 =",d1)
print("ID of d1 is", id(d1))
d2 = {"bobe":3, "tom":30}
print("d2 =",d2)
print("ID of d2 is", id(d2))
# Member
print("tom" in d1) # True
print("tom" not in d1) # False
# Relational
print(d1 == d2) # True
print(d1 != d2) # False
|
from django.core.mail import send_mail
from rest_framework.views import APIView
import bcrypt
from decouple import config
from ...models.user import User
from ...models.customer import Customer
from ...utils.helper import random_string_generator, send_email, customer_message
from ...verification.customer_validator i... |
import mnist
import numpy as np
import matplotlib.pylab as plt
import umap
from persistence_diagram import persistence
from plot_persistent_homology import plot_diagrams
if __name__ == '__main__':
np.random.seed(1)
num_neurons = 1024
bc_base = './results/barcode-experiment-MNIST-'
h0_base = './resul... |
import torch
from .registry import DATASETS
from .base import BaseDataset
@DATASETS.register_module
class ContrastiveDataset(BaseDataset):
"""Dataset for rotation prediction
"""
def __init__(self, data_source, pipeline):
super(ContrastiveDataset, self).__init__(data_source, pipeline)
def _... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-30 10:45
from __future__ import unicode_literals
from django.db import migrations
def load_user_data_fields(apps, schema_editor):
UserDataFields = apps.get_model('consent', 'UserDataFields')
UserDataFields(name='Roll Number', slug='roll_number', de... |
import torch
from nndct_shared.nndct_graph import Tensor
from nndct_shared.quantization import maybe_get_quantizer
from nndct_shared.quantization import process_inputs_and_params
from nndct_shared.quantization import post_quant_process
import pytorch_nndct.utils as py_utils
from pytorch_nndct.utils import TorchOpClassT... |
# DOCUMENTATION
# IMPORTS
# FUNCTIONS
def find_names(contacts_dictionary, number):
output_list = []
for name in contacts_dictionary:
if contacts_dictionary[name] == number:
output_list.append(name)
return " ".join(output_list)
def print_contacts(contacts_dictionary):
for name in... |
# -*- coding: utf-8 -*-
"""
kaftools.sparsifiers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides sparsifier classes for Sparsification criteria.
Currently supports:
- Novelty criterion
- Approximate Linear Dependency (ALD)
Not all filters support all sparsifiers. Be sure to check the info sheet
for detailed compari... |
"""
find options of deribit
"""
from archon.exchange.deribit.Wrapper import DeribitWrapper
import archon.config as config
import archon.broker as broker
import archon.exchange.exchanges as exc
from datetime import datetime
abroker = broker.Broker(setAuto=False)
abroker.set_keys_exchange_file(exchanges=[exc.DERIBIT])... |
''' Tensor initializers
The functions presented here are just tiny wrappers around
`numpy` functions, in order to make them compatible with nujo.
'''
from nujo.init.basic import *
from nujo.init.random import *
|
from abc import ABC, abstractmethod
import logging
import yaml
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
class LimitsReader(ABC):
@abstractmethod
def get_p_e_max_limit(self):
"""Get P/E max limit."""
@abstractmethod
def get_roe_min_limit(self):
"""Get ROE ... |
check_solution("console_hello.exe", f"int: {a_random_int}")
|
"""
This file defines a series of constants that represent the values used in
the API's "helper" tables.
Rather than define the values in the db setup scripts and then make db calls to
lookup the surrogate keys, we'll define everything here, in a file that can be
used by the db setup scripts *and* the application code... |
import random
import tempfile
from machi import MachiStore
def test_smoke():
testdir = tempfile.TemporaryDirectory()
machi = MachiStore(maxlen=37, temp=True)
try:
key = machi.append(b"1")
data = machi.get(*key)
assert b"1" == data
machi.trim(*key)
data = machi.ge... |
class Agent:
def __init__(self):
self.property_list = []
def display_properties():
for property in self.property_list:
property.display()
|
from flask_restful import Resource, reqparse
from flask_jwt_extended import (jwt_optional, get_jwt_identity,
fresh_jwt_required, jwt_required,
get_jwt_claims)
from src.user import User
from src.db import db
from typing import List
proj_allocation = db.Ta... |
/* {"title":"multiplication de matrices","platform":"python","tags":["python"]} */
_VIEW_A = "showArray2D(A, rowCursors=[i], colCursors=[k], rows=2, cols=2, width=.33)"
_VIEW_B = "showArray2D(B, rowCursors=[k], colCursors=[j], rows=2, cols=2, width=.33)"
_VIEW_C = "showArray2D(C, rowCursors=[i], colCursors=[j], rows=2,... |
"""Test for the longest_prefix_match definitions."""
from ipaddress import AddressValueError, NetmaskValueError
import pytest
from netutils.route import NoRouteFound, longest_prefix_match
def test_longest_prefix_match():
"""Test Success."""
lookup = "10.1.1.245"
routes = [{"network": "192.168.1.1", "mas... |
class Message1:
_field1: str
_field2: int
def __init__(self, **kwargs):
self._field1 = kwargs.get('field1', str())
self._field2 = kwargs.get('field2', int())
@property
def field(self) -> str:
return self._field1
def __str__(self):
return "Message1:(field1: {} f... |
import staging_schemas as ss
from google.oauth2 import service_account
from google.cloud import bigquery
from google.cloud import exceptions
import argparse
import logging
logging.basicConfig(level=logging.INFO)
def get_client(project_id, _service_account):
"""
Get client object based on the project_id.
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import csv
import datetime
import sys
import time
reload(sys)
sys.setdefaultencoding("utf-8")
from googleapiclient.discovery import build
from healthtrends.decorators import retry, timeit... |
from social.backends.appsfuel import AppsfuelOAuth2 as AppsfuelBackend, \
AppsfuelOAuth2Sandbox as AppsfuelSandboxBackend
|
"""
Server for people directory
"""
from datetime import datetime, timedelta
from functools import partial
import json
import logging
import re
import os
from tornado.web import RequestHandler, HTTPError
from tornado.escape import xhtml_escape
from rest_tools.server import RestServer, from_environment
from .people i... |
from smite import SmiteClient
from smite import Endpoint
# Create a new instance of the client
smite = SmiteClient(1700, '2djsa8231jlsad92ka9d2jkad912j')
# Print JSON data for all of the gods in the game on PC
print(smite.get_gods())
# Make the library use the Xbox endpoint for future requests
smite._switch_endpoint(... |
import collections
import netaddr
from oslo_log import log
from oslo_config import cfg
from oslo_utils import timeutils
from neutronclient.common import exceptions as neutron_exc
from ceilometer.agent import plugin_base
from ceilometer import nova_client, neutron_client
from ceilometer import sample
from ceilometer... |
# A neural network implementation.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def softmax(logits):
exponentials = np.exp(logits)
return exponentials / np.sum(exponentials, axis=1).reshape(-1, 1)
def sigmoid_gradient(sigmoid):
return np.multiply(sigmoid, (1 - sigmoid))
def lo... |
name = 'python'
version = '2.7.10'
tools = ['python']
variants = [
['platform-linux', 'arch-x86_64', 'os-CentOS-6']
]
def commands():
env.PATH.append('/home/cmartin/opt/python/python2.7.10/bin')
|
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from pygments.token import Token
from nubia import context
from nubia import statusbar
from pandas import DataFrame
from suzieq.version import SUZIEQ_VERSION
class NubiaSuzieqStatusBar(statusbar.StatusBar):
def __init__(self, ctx):
self._last_status = None
self.ctx = ctx
def get_rprompt_tok... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Bayesian Blocks for Time Series Analysis
========================================
Dynamic programming algorithm for solving a piecewise-constant model for
various datasets. This is based on the algorithm presented in Scargle
et al 2012 [1]_. This cod... |
# Copyright (c) 2014 Thomas Scholtes
# 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 limitation the
# rights to use, copy, modify, merge, publish, dist... |
import logging
import os
import shutil
import sys
import gym
import os.path
import tensorflow as tf
from model import universeHead
from pretrain_cifar.data import Cifar10
from pretrain_cifar import summary, Experiment
logger = logging.getLogger(__name__)
def train(opt):
#######################... |
import os
import shutil
import subprocess
import torch
from src import log_setup
from src.srt.infer import generate_srt
from src.media_convertor import media_conversion
LOGGER = log_setup.get_logger(__name__)
def noise_suppression(dir_name, denoiser_path):
cwd = os.getcwd()
os.chdir(denoiser_path)
subp... |
from scene_helper import *
import sys
print('=== Wineglass Scene ===',file=sys.stderr)
w=1920
h=1080
obj=[]
light=[]
#wall_mat=Material((0.9,0.9,0.9),(0.07,0.07,0.07),0.3)
blue_wall_mat=Material((0,0,1),(0,0,0.7),0.3)
red_wall_mat=Material((0.85,0,0),(0.07,0,0),0.3)
mr_mat=MirrorMaterial((0.95,0.95,0.95))
gold_metal_ma... |
import requests
class Payload:
"""
This would instantiate a new payload.
The reason to have this as a class is that there might be verifications and checks to be peformed on the payload to ensure it is valid.
We will include those verifications here, although for now it is going to be a simple t... |
import pandas as pd
import numpy as np
import h5py
import geopandas as gp
import os
import datetime
import dask
import dask.dataframe as dd
from tqdm import tqdm
def latlon_iter(latdf, londf, valdf, date):
out_df = pd.concat([latdf, londf, valdf], axis = 1, keys = ['lat', 'lon', 'sst']).stack().reset_index().drop(... |
import os
from config import db
from models import Product
# # Objetos iniciados ao criar o database
PRODUCTS = [
{"name": "Samsung Galaxy S11", "brand": "Samsung", "price": 3400.00, "stock": 150},
{"name": "Samsung Galaxy M21s", "brand": "Samsung", "price": 1400.00, "stock": 1150},
{"name": "Redmi Note 10... |
import numpy as np
from tqdm import tqdm
from math import sqrt
def read_file(path='nn.txt'):
with open(path) as f:
num_cities = int(f.readline().strip('\n'))
graph = {}
for line in f.readlines():
temp_list = list(map(float, line.strip('\n').split(' ')))
gra... |
# Copyright (c) 2021 Intel Corporation.
#
# 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 limitation the rights
# to use, copy, modify, merge, publish, ... |
# -*- coding: utf-8 -*-
#
# PySceneDetect: Python-Based Video Scene Detector
# ---------------------------------------------------------------
# [ Site: http://www.bcastell.com/projects/PySceneDetect/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
# [ Documentation: http://py... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... |
# -*- coding: utf-8 -*-
"""Flux Calculation class tests.
This script tests the operation of the Flux Calculation Class.
Created on Fri Apr 16 11:53:12 2021
@author: denis
"""
from PSF import Point_Spread_Function
from CHC import Concrete_Channel_1
import pytest
from astropy.table import Table
from photutils.datas... |
import polymath as pm
from .template_utils import _get_single_node_indices
from polymath.srdfg.util import squeeze_shape
from numbers import Integral
import numpy as np
import functools
class tensor_transpose(pm.Template):
def define_graph(self, data, out, perm=None):
temp = pm.transpose(data, perm)
... |
from argparse import ArgumentParser
import logging
from .exception import RfcDLArgumentException
logger = logging.getLogger("rfcdl")
def parse_arguments():
parser = ArgumentParser(prog="rfcdl", description="A tool for downloading RFCs in high-speed.")
parser.add_argument("-v", "--debug", action="store_true"... |
#!/usr/bin/env python
import sys
from optparse import OptionParser
def _get_opt_parser():
msg_usage = '''%prog -o <origin_file> -l <latest_file>'''
opt_parser = OptionParser(msg_usage)
opt_parser.add_option(
"-o", "--origin_file", action="store", type="string", default=None,
dest="origin... |
from BooleanEncoding import *
identity = lambda a: a;
kestral = lambda x: lambda y: x;
kite = lambda x: lambda y: y;
mockingbird = lambda f: f(f);
cardinal = lambda f: lambda a: lambda b: f(b)(a);
# function composition B-Combinator
bluebird = lambda f: lambda g: lambda x: f(g(x));
# T-Combinator
thrush = lambda... |
#!/usr/bin/env python
# setup.py for Pycolor
from distutils.core import setup
setup(name='Pycolor',
version='1.2.1',
description='Ansi color for python',
author='Will Drach',
license='Beerware',
author_email='will.drach@live.com',
url='http://www.drach.co/pycolor',
py_modules... |
#!/usr/bin/env python
#
# Copyright 2017 Import.io
#
# 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 ... |
"""
Django settings for PcapDB interface project.
The basic model of the PCAPdb interface is as follows:
- The search head/s are the only hosts that serve the HTML based interface.
- The search head also provides an API to all functionality served by the HTML interface.
- Authentication and permissions are governed... |
import pygame as pg
import random
import load_images
import variables
from VisualManagement import *
from variables import *
pg.init()
pg.display.set_caption('Backgammon Project 2')
screen_size = (900, 790) # a tuple of size (width, height)
screen = pg.display.set_mode(screen_size)
# import board images:
white_pawn... |
# TODO: un-subclass dict in favor of something more explicit, once all regular
# dict-like access has been factored out into methods
class LineManager(dict):
"""
Manages multiple release lines/families as well as related config state.
"""
def __init__(self, app):
"""
Initialize new line... |
from sys import stdout, stderr
from scell import Selector
from pytest import fixture
import scell.core
@fixture(autouse=True)
def mock_select(monkeypatch):
def select(rlist, wlist, xlist, timeout=None):
if not timeout and not rlist and not wlist:
raise RuntimeError
return rlist, wlist,... |
import inspect
import ast
from types import FunctionType
import hashlib
from typing import List
import astunparse
from pyminifier import minification
class VerfunException(Exception):
pass
def version_hash_for_function(fn: FunctionType) -> str:
abstract_syntax_tree = ast.parse(inspect.getsource(fn)).body[0... |
from pyrogram import Client
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram.errors import MessageNotModified
from functions.functions import speed_test, disk_space
start_and_help = InlineKeyboardMarkup([[InlineKeyboardButton(text='Creator 🦾', url='https://t.me/M... |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... |
# -*- coding: utf-8 -*-
#
# test_radkdict.py
# cjktools
#
import unittest
from six.moves import StringIO
from cjktools.resources.radkdict import RadkDict
def suite():
test_suite = unittest.TestSuite((
unittest.makeSuite(RadkdictTestCase)
))
return test_suite
SAMPLE = \
"""
$ 一 1
偏
$ | 1
偏
$ 化... |
"""
Funkcija akceptē vienu argumentu - temperatūru Celsija grādos,
un atgriež temperatūru Kelvina grādos. Zemākā temperatūra
Kelvina grādos var būt 0, tādēļ, ja aprēķinātā temperatūra ir
zemāka, atgriež 0.
Argumenti:
t {int vai float} -- temperatūra Celsija grādos
Atgriež:
int vai float -- temperatūra Kelvina ... |
"""
verktyg_server.tests.test_ssl
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright:
(c) 2015 by Ben Mather.
:license:
BSD, see LICENSE for more details.
"""
import unittest
class SSLTestCase(unittest.TestCase):
pass
|
class Test:
x = 10
if __name__ == '__main__':
a = Test()
a.x = 1
b = Test()
assert a.x == 'update value'
assert b.x == 'update value'
Test.x = 5
c = Test()
assert a.x == 'update value'
assert b.x == 'update value'
assert c.x == 'update value'
|
from lektor.types import Type
from lektor.environment import PRIMARY_ALT
from lektor.i18n import get_i18n_block
class FakeType(Type):
def value_from_raw(self, raw):
return None
def to_json(self, pad, record=None, alt=PRIMARY_ALT):
rv = Type.to_json(self, pad, record, alt)
rv['is_fake... |
# -*- coding: utf-8 -*-
"""Syslog sender provider"""
from datetime import datetime
from builtins import input
from .base_sender import BaseSender
class SyslogSender(BaseSender):
"""Generate a lot of events from/for Syslog"""
def __init__(self, engine, template, **kwargs):
BaseSender.__init__(self, eng... |
teste = list()
teste.append('Pedro')
teste.append(18)
galera = list()
galera.append(teste[:])
teste[0] = 'Gustavo'
teste[1] = 40
galera.append(teste[:])
print(galera)
maisteste = [['Pedro', 18], ['Joao', 16], ['Jaqueline', 41]]
print(maisteste[0])
print(maisteste[1][1])
for p in maisteste:
print(f'{p[0]} tem {p[1]}... |
from torch.distributions import Categorical
import torch
def sample_action(logits: torch.tensor, return_entropy_log_prob=False):
prob_dist = Categorical(logits=logits)
y_preds = prob_dist.sample()
if return_entropy_log_prob:
return y_preds, prob_dist.log_prob(y_preds), prob_dist.entropy()
retu... |
from scipy.stats import truncnorm
import matplotlib.pyplot as plt
import numpy as np
import math
# import seaborn as snc
fig = plt.figure()
ax1 = fig.add_subplot(131)
ax2 = fig.add_subplot(132)
ax3 = fig.add_subplot(133)
no_of_req = 2600
freq4 = {1.0: 450, 2.0: 894, 3.0: 869, 4.0: 387}
mec4 = [3.0, 4.0, 3.0, 2.0, 4.0... |
import xlrd
import os
import data
class NaturePredict(object):
"""http://www.nature.com/msb/journal/v7/n1/full/msb201126.html"""
def __init__(self, directory=None):
if not directory:
directory = data.source_data_dir('nature-predict')
self.directory = directory
self.ind... |
# build graph from cleaned (only contains actor id and receiver id of each tx)
# & normalized venmo dataset
import csv
import networkx as nx
import os
import metis
dg = nx.MultiDiGraph()
fp = open("venmo_hybrid_algo_metis_part.csv", "r") # , encoding='utf-8')
csv_file = csv.reader(fp)
for row in csv_file:
dg.add... |
from .base import *
from .mixins import *
from .decorators import *
@Singleton
class CommandService(AjaxMixin):
"""
This service exists to register the available commands and provide a way of
routing to the correct command class based on the command name received
by the front end code.
"""
# the name of the fie... |
class Solution:
def numberOfSteps (self, num: int) -> int:
binary = bin(num)[2:]
ones = binary.count("1")
total = len(binary)
return ones + total - 1 |
import re
from org.zaproxy.zap.extension.script import ScriptVars
''' find posible Server Side Template Injection using Hunt Methodology'''
def scan(ps, msg, src):
# Test the request and/or response here
if ScriptVars.getGlobalVar("hunt_pssti") is None:
ScriptVars.setGlobalVar("hunt_pssti","init")
... |
from Configurables import DaVinci
DaVinci().DataType = '2012'
DaVinci().Simulation = True
DaVinci().TupleFile = 'mc.root'
from Configurables import LHCbApp
LHCbApp().CondDBtag = "sim-20130522-1-vc-md100"
LHCbApp().DDDBtag = "dddb-20130829-1"
|
import numpy as np
class Conv1DT:
def __call__(self, x, weight, bias, stride, padding):
x = x.T
w = weight.transpose(2, 0, 1)
kernel_len, _, outchan = w.shape
temp = np.dot(x, w) # [inlen, kernel, outchan]
temp = temp.reshape(-1, outchan)
temp = np.pad(temp, ((ke... |
import sys
import oisin
filename = "input/alices.txt"
try:
filename = sys.argv[1]
except IndexError:
pass
oisin.balladize(
oisin.load(filename),
meter=oisin.iambic(4, 'aabbccdd'),
step=50,
order=3)
|
# -*- coding: utf-8 -*-
# Copyright 2017 Leo Moll and Dominik Schlösser
#
# -- Imports ------------------------------------------------
import xbmcgui
import xbmcplugin
from resources.lib.film import Film
from resources.lib.settings import Settings
# -- Classes ------------------------------------------------
class ... |
import logging
log = logging.getLogger(__name__)
from uasyncio import Loop as loop, sleep_ms
from board import act_led
class Blinker:
def __init__(self, mqclient, topic, period):
self.mqclient = mqclient
self.topic = topic
self.period = period
async def blinker(self):
while T... |
if __name__ == "__main__":
main = int(input("Que ejercicio deseas realizar(1,2 o 3):"))
if main == 1:
ciudad = str(input("En que ciudad quieres que se produzca la tragedia(NewYork o LosAngeles)?: "))
edificios = []
persona = []
if ciudad == "NewYork":
from ... |
import requests
import json
from requests.auth import HTTPBasicAuth
class Elastic(object):
def __init__(self):
self.ELASTIC_SEARCH_URL = "https://c-c9qc3vfnqlo9av21d79a.rw.mdb.yandexcloud.net:9200/"
self.LOGIN = "***"
self.PASSWORD = "***"
self.INDEX_NAME = "gpn_01"
self.... |
import os
import os.path
import sys
restools_root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(restools_root_path, 'thequickmath'))
sys.path.append(os.path.join(restools_root_path, 'pycomsdk'))
sys.path.append(os.path.join(restools_root_path, 'reducedmodels'))
|
"""
Tools to automate browsing (requires Firefox)
"""
try:
from urllib.parse import quote_plus # Python 3
except ImportError:
from urllib import quote_plus # Python 2
import os
import traceback
from sys import platform as _platform
from selenium import webdriver
from selenium.webdriver.co... |
from ..utils import Object
class UpdateBasicGroupFullInfo(Object):
"""
Some data from basicGroupFullInfo has been changed
Attributes:
ID (:obj:`str`): ``UpdateBasicGroupFullInfo``
Args:
basic_group_id (:obj:`int`):
Identifier of a basic group
basic_group_full_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created: 2018
Author: A. P. Naik
Description: Code to fit galactic disc component for SPARC galaxies, and store
parameters in text file
"""
import spam
from scipy.optimize import curve_fit
import numpy as np
from scipy.constants import G
from scipy.special import i0, i... |
from .base_backend import BaseBackend
class MlpBackend(BaseBackend):
def __init__(self, inpmulti, hidmulti, outmulti, learning_rate, inp96, hid96, out96, path, buffsize, mean, std, statspath):
from neupre.misc.builders import build_model_mlp
super(MlpBackend, self).__init__(int(buffsize))
... |
from .handler import Handler
class NameHandler(Handler):
def handle(self, *args):
print("NH" + str(args))
def name(self):
return "name"
|
from lucas_kanade.corridor import corridor_interpolation
from lucas_kanade.sphere import sphere_interpolation
# Corridor dataset interpolation
corridor_interpolation(N=5)
# Sphere dataset interpolation
sphere_interpolation(N=5)
|
"""
Tests for the `csvvalidator` module.
"""
import logging
import math
from csvvalidator import CSVValidator, VALUE_CHECK_FAILED, MESSAGES,\
HEADER_CHECK_FAILED, RECORD_LENGTH_CHECK_FAILED, enumeration, match_pattern,\
search_pattern, number_range_inclusive, number_range_exclusive,\
VALUE_PREDICATE_FAL... |
import argparse
import asyncio
import logging
import rasa.utils
from policy import RestaurantPolicy
from rasa.core import utils
from rasa.core.agent import Agent
from rasa.core.policies.memoization import MemoizationPolicy
from rasa.core.policies.mapping_policy import MappingPolicy
logger = logging.getLogger(__name__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.