text stringlengths 1 927k |
|---|
from pathlib import Path
import shutil
from jinja2 import Template
from invoke import task
import jupytext
_TARGET = Path('~', 'dev', 'ploomber').expanduser()
@task
def setup(c, from_lock=False):
"""Create conda environment
"""
if from_lock:
c.run('conda env create --file environment.yml --force... |
# file openemory/publication/tests.py
#
# Copyright 2010 Emory University General Library
#
# 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/LICE... |
import json
import pytest
import responses
import requests
import sys
import pandas
from models.exchange.ExchangesEnum import Exchange
sys.path.append('.')
# pylint: disable=import-error
from models.PyCryptoBot import PyCryptoBot
from models.exchange.coinbase_pro import AuthAPI, PublicAPI
app = PyCryptoBot(exchange=... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2016, Camptocamp SA
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
#... |
# -----------------------------------------------------------------------------
# Builder
# -----------------------------------------------------------------------------
# Team: DataHub
# -----------------------------------------------------------------------------
# Author: Maxime Sirois
# ----------------------------... |
import os
import subprocess
import sys
import pytest
sys.path.append("tests/python")
import testing as tm
import test_demos as td # noqa
@pytest.mark.skipif(**tm.no_cupy())
def test_data_iterator():
script = os.path.join(td.PYTHON_DEMO_DIR, 'data_iterator.py')
cmd = ['python', script]
subprocess.ch... |
from dmarc_metrics_exporter.dmarc_metrics import (
Disposition,
DmarcMetrics,
DmarcMetricsCollection,
Meta,
)
from dmarc_metrics_exporter.metrics_persister import MetricsPersister
def test_roundtrip_metrics(tmp_path):
metrics_db = tmp_path / "metrics.db"
metrics = DmarcMetricsCollection(
... |
# -*- coding: utf-8 -*-
"""Processor for Bgee."""
import os
import pickle
from pathlib import Path
from typing import Union
import pyobo
from indra_cogex.representation import Node, Relation
from indra_cogex.sources.processor import Processor
class BgeeProcessor(Processor):
"""Processor for Bgee."""
name... |
import numpy as np
def read_ds9region(ds9regfile):
"""
Assume ds9regfile in the format as ds9, and coordinate system as image
"""
out = {}
f = open(ds9regfile,'r')
for i,ii in enumerate(f.readlines()):
if i < 3:
continue
x,y,_ = np.array(ii.split('(')[1].split(')')[0... |
import uuid
import os
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from django.conf import settings
def recipe_image_file_path(instance, filename):
"""Generate file path for new recipe image"""
... |
"""
Base settings to build other settings files upon.
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (techfest_management/config/settings/base.py - 3 = techfest_management/)
APPS_DIR = ROOT_DIR.path('techfest_management')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', defa... |
from django.contrib import admin
# Register your models here.
from .models import Todo
admin.site.register(Todo) |
from typing import List, Dict
from ttt.helper_util import (PositionOccupiedException,
InvalidCellPosition, AllMovesExhausedWithNoWinner,
BgColors)
from ttt.player import Player
class Move(object):
"""
Class used to identify a move being selected by th... |
from mhvdb2 import app
app.run() |
#!/usr/bin/env python
"""
==================================
dMRI: DTI - Diffusion Toolkit, FSL
==================================
A pipeline example that uses several interfaces to perform analysis on
diffusion weighted images using Diffusion Toolkit tools.
This tutorial is based on the 2010 FSL course and uses data... |
from copy import deepcopy
import asyncio
import json
import pandas as pd
import streamlit as st
from structlog import get_logger
from helpers import (
fromtimestamp,
show_weather,
WeatherItem,
gather_one_call_weather_data,
clean_time,
)
log = get_logger()
st.set_page_config(
layout="wide",
... |
#!/usr/bin/env python
import argparse
import logging
import sys
import os
import re
import yaml
from jinja2 import Template, Environment, FileSystemLoader
# Goals:
# k8s_container_cpu_exceeding_request: CPU exceeds request over 10 minutes - if cpu request configured
# k8s_container_memory_exceeding_request: Memory exc... |
""" Model of ACC with FCW and IDM+ to take over from Xiao et al. (2017).
Creation date: 2020 08 12
Author(s): Erwin de Gelder
Modifications:
"""
import numpy as np
from .acc import ACC, ACCParameters, ACCState
from .idm import IDMParameters
from .idmplus import IDMPlus
class ACCIDMPlusParameters(ACCParameters):
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import namedtuple, OrderedDict, defaultdict
from dateutil.relativedelta import relativedelta
from odoo.tools.misc import split_every
from psycopg2 import OperationalError
from odoo import api, fields, m... |
from django.apps import AppConfig
class ContatoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'contato' |
# -*- coding: utf-8 -*-
"""Basic functions for PiNN models"""
import tensorflow as tf
from pinn.utils import pi_named
def export_model(model_fn):
# default parameters for all models
from pinn.optimizers import default_adam
default_params = {'optimizer': default_adam}
def pinn_model(params, **kwargs):
... |
# Corret cost in produceSale spreadsheet
import openpyxl
# The product types and their updated prices
PRICE_UPDATE = {
'Garlic': 3.17,
'Celery':1.19,
'Lemon': 1.27
}
wb = openpyxl.load_workbook('produceSales.xlsx')
ws = wb.get_sheet_by_name('Sheet')
# loop through the rows and update the prices, skip the fi... |
import demistomock as demisto
""" API RAW RESULTS """
MACHINE_OUTPUTS = {
"status": "SUCCESS",
"message": "",
"data": {
"evidenceMap": {
"reportedByAntiMalwareEvidence": 1
},
"resultIdToElementDataMap": {
"-1879720569.-2277552225461983666": {
... |
from unittest import TestCase
import os
import numpy as np
import glimslib.utils.file_utils as fu
from glimslib import fenics_local as fenics, config
from glimslib.simulation_helpers.helper_classes import FunctionSpace, TimeSeriesMultiData
class TestTimeSeriesMultiData(TestCase):
def setUp(self):
# Doma... |
#!/usr/bin/env python
from __future__ import unicode_literals
import base64
import json
import mimetypes
import netrc
import optparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from youtube_dl.compat import (
compat_basestring,
compat_input,
compa... |
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Davide Gessa
'''
MIT License
Copyright (c) 2021 Davide Gessa
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 li... |
import os
import uuid
from django.core.files.storage import default_storage
from django.utils.text import slugify
from .models import StdImageField, StdImageFieldFile
class UploadTo:
file_pattern = "%(name)s%(ext)s"
path_pattern = "%(path)s"
def __call__(self, instance, filename):
path, ext = o... |
'''
Author: Ashutosh Panigrahi
Year: 2021
Version: 0.0.1
'''
#This piece of code detect the face (image in png/jpg or else given) given.
import __future__
import click
import os
import re
import face_recognition.api as fcrec
import multiprocessing
import sys
import itertools
def print_result(filename, location):
... |
#!/opt/workflow/bin/python2.7
#
# Copyright 2013-2016 Edico Genome Corporation. All rights reserved.
#
# This file contains confidential and proprietary information of the Edico Genome
# Corporation and is protected under the U.S. and international copyright and other
# intellectual property laws.
#
# $Id$
# $Author$
#... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from reinforce import Reinforce
from model import CriticNet
import feh_simulator.simulator as gym
class A2C(Reinforce):
# Implementation of N-step Advantage Actor Critic.
# This class inherits the Reinforce class, so ... |
# Copyright 2015-2016 Cisco Systems, Inc.
# 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 ... |
import tensorflow as tf
class RNVP(tf.Module):
"""Affine half (aka Real Non-Volume Preserving) flow (x = z * exp(s) + t),
where a randomly selected half z1 of the dimensions in z are transformed as an
affine function of the other half z2, i.e. scaled by s(z2) and shifted by t(z2).
From "Density estim... |
from glob import glob
import config
import errno
import os
def unique_id(msg):
ext = '.txt'
f = glob("*"+ext)[0]
num_trail = int(f.split(".")[0])
newf = "./" + str(num_trail+1) + ext
os.rename(f, newf)
outdir = os.path.join("../weights", config.summary_prefix+"%02d"%num_trail)
mkdir_p(outdi... |
from sqlalchemy.orm import joinedload, contains_eager, subqueryload
from clld.web import datatables
from clld.web.datatables.base import Col, LinkCol, DetailsRowLinkCol, IdCol
from clld.web.datatables.value import ValueNameCol
from clld.db.meta import DBSession
from clld.db.models import common
from clld.db.util impor... |
"""Modules with base classes and utilities for pandas objects, such as broadcasting.
## Array wrapper
vectorbt's functionality is based upon the ability to perform the most essential pandas operations
using NumPy+Numba stack. One has to convert the Series/DataFrame into the NumPy format, perform
the computation, and ... |
from .model_wrappers import model_wrap, register_wrapper, IModelWrapper, BaseModelWrapper |
from functools import partial
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn.apionly as sns
from ..analysis.csv_analysis import analyze_data, load_surveys
from ..data.survey_utils import ExperimentType
from .latexify import latexify, figure, fig_size
fro... |
mai_idade = homens = fem_men_20 = 0
while True:
print('-'*30)
print('CADASTRE UMA PESSOA')
# inserir dados
idade = int(input('Idade: '))
sexo = input('Sexo [M/F]: ').strip().upper()[0]
while sexo not in 'MF':
sexo = input('ERRO. Digite novamente o sexo: ').strip().upper()[0]
# veri... |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test the BIP66 changeover logic
#
from test_framework.test_framework import CivilbitTestFramework
fr... |
from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
# Anonymous Expansion {{{#
class _AnonBase(_VimTest):
args = ''
def _extra_vim_config(self, vim_config):
vim_config.append('inoremap <silent> %s <C-R>=UltiSnips#Anon(%s)<cr>'
% (EA, self.arg... |
from sly import Lexer
class YsharpLexer(Lexer):
tokens = {
ID,
FLOAT,
INT,
FUNC,
CLASS,
STRING,
EQ_GREATER,
EQ_LESS,
EQEQ,
PYTHON_CODE,
COLON_COLON,
IF,
ELSE,
TRUE,
FALSE,
NOT_EQEQ,
... |
from boardgame import BaseBot, BaseBoard, BasePlayer, Move
from hnefatafl.engine import PieceType, variants
from hnefatafl import MODEL_PATH, MODEL_CONFIG_PATH
from alphazero.GenericPlayers import MCTSPlayer, NNPlayer
from threading import Lock
import os
import importlib
import random
import pyximport, numpy
pyximp... |
from peachy.geo import ShapeEnum
# Collision functions are alphabetical but prioritze rectangles because
# they are most common
"""The max tolerance for floating point errors."""
TOLERANCE = 0.001
def is_between(x, a, b):
return min(a, b) <= x <= max(a, b)
def rect_to_vector_segments(rect):
x, y, width, h... |
"""
This file offers the methods to automatically retrieve the graph Ralstonia insidiosa.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein as... |
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import pgettext_lazy
from ...error_codes import PaymentErrorCode
from ...interface import PaymentData
class BraintreePaymentForm(forms.Form):
amount = forms.DecimalField()
# Unique transaction identifie... |
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.associationproxy import association_proxy
from dataservice.extensions import db
from dataservice.api.common.model import Base, KfId
class CavaticaTask(db.Model, Base):
"""
CavaticaTask entity represents an executed Cavatica task
:param ... |
# Create a script to run a random hyperparameter search.
import copy
import getpass
import os
import random
import numpy as np
LIN = "LIN"
EXP = "EXP"
SS_BASE = "SS_BASE"
# Instructions: Configure the variables in this block, then run
# the following on a machine with qsub access:
# python make_sweep.py > my_sweep.s... |
from contextlib import contextmanager
from itertools import count
from jeepney import HeaderFields, Message, MessageFlag, MessageType
class MessageFilters:
def __init__(self):
self.filters = {}
self.filter_ids = count()
def matches(self, message):
for handle in self.filters.values():
... |
from Usina import Usina;
from RecebeDados import RecebeDados;
class Termica(Usina):
def __init__(self, recebe_dados, abaTerm, offset, iTerm, nMeses, nMesesPos, continuidade=False):
# define fonte_dados como o objeto da classe RecebeDados e o nome da aba com as usinas UHE
self.nomeAba ... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueEr... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# -------------------------------------------------------------------
# Copyright (c) 2010-2021 Denis Machard
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... |
"""The tests for the notify smtp platform."""
import re
import unittest
from homeassistant.components.smtp.notify import MailNotificationService
from tests.async_mock import patch
from tests.common import get_test_home_assistant
class MockSMTP(MailNotificationService):
"""Test SMTP object that doesn't need a wo... |
__author__ = 'mason'
from domain_orderFulfillment import *
from timer import DURATION
from state import state
import numpy as np
'''
This is a randomly generated problem
'''
def GetCostOfMove(id, r, loc1, loc2, dist):
return 1 + dist
def GetCostOfLookup(id, item):
return max(1, np.random.beta(2, 2))
def Ge... |
import numpy as np
from tqdm import tqdm
import torch
import pdb
from typing import Iterator
from allennlp.data import Instance
from allennlp.data.dataset_readers import DatasetReader
from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer, PretrainedTransformerIndexer
from allennlp.data.fields impo... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : setting.py
@Desc :
@Project : orfd-platform
@Contact : thefreer@outlook.com
@License : (C)Copyright 2018-2019, TheFreer.NET
@WebSite : www.thefreer.net
@Modify Time @Author @Version
------------ ------- ... |
"""cssProject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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-ba... |
import numpy as np
import librosa
# import pdb
import wget
local_config = {
'batch_size': 64,
'load_size': 22050*20,
'phase': 'extract'
}
def get_audio(audio_link):
file_name = audio_link.split('/')[-1]
save_location = "/Users/sanjitjain/projects/soundnet_tf/da... |
#
# Copyright 2016 the original author or 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
"""Generates an upstream.yaml from a config.yaml and a GitHub release URL
"""
import argparse
import os
from tempfile import TemporaryDirectory
import yaml
import zipfile
import gftools.packager
from gftools.builder import GFBuilder
from strictyaml import as_document
from gftools.utils import download_file
from fontT... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""
Ory Kratos API
Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the admini... |
from django.contrib import admin
from . import models
class DatasetVersionInline(admin.TabularInline):
model = models.DatasetVersion
class DatasetAdmin(admin.ModelAdmin):
inlines = [
DatasetVersionInline,
]
admin.site.register(models.Repository)
admin.site.register(models.Dataset, DatasetAdmi... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'h:\projects\jukebox-core\src\jukeboxcore\gui\widgets\releasewin.ui'
#
# Created: Mon Nov 03 16:58:04 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCor... |
dataset_paths = {
'celeba_train': '/scratch/users/abaykal20/sam/SAM/mmcelebhq/train_images/',
'celeba_test': '/scratch/users/abaykal20/sam/SAM/mmcelebhq/test_images/',
'celeba_train_sketch': '',
'celeba_test_sketch': '',
'celeba_train_segmentation': '',
'celeba_test_segmentation': '',
'ffhq': '/datasets/CelebAMa... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.factor
~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Factor language.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, default, words
from ... |
'''
https://leetcode.com/problems/binary-tree-maximum-path-sum/
124. Binary Tree Maximum Path Sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has
an edge connecting them. A node can only appear in the sequence at most once. Note that the path does n... |
from textwrap import dedent
import pytest
from sqlalchemy import Column, ForeignKey, String, Text
from sqlalchemy.orm import relationship
from flask_filealchemy import FileAlchemy, LoadError
def test_directory_does_not_exist(db):
app = db.get_app()
class Author(db.Model):
__tablename__ = 'authors'
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.15.9
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fr... |
# Generated by Django 2.1.11 on 2020-06-08 07:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('examples', '0015_img_data_img_folder_path'),
]
operations = [
migrations.AddField(
model_name='parsed_data',
name='... |
from provider.facebook import FacebookProvider
providers = {
'facebook': FacebookProvider
}
def get_provider(provider):
if provider in providers:
return providers[provider]
else:
raise NotImplementedError('no provider named "%s"' % provider) |
# -*- coding: utf-8 -*-
# Copyright 2012 splinter 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 re
from lxml.cssselect import CSSSelector
from zope.testbrowser.browser import Browser, ListControl
from splinter.element_list i... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def ou(n):
s = 0.0
if n < 2:
return 0
else:
for j in range(n, 0, -2):
s += (1.0 / j)
print j
return s
def ji(n):
s = 0.0
if n < 1:
return 0
else:
for i in range(n, 0, -2):
s ... |
#!/usr/bin/env python3
import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
sys.path.append('..')
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.python.framework import meta_graph
from mold import Scaling
from gallery import Gallery
from chest import *
class Model:
def __init__ (sel... |
'''
A system for retrieving and assigning tasks for the bot as well as updating
their statuses once acted up. This file contains two abstract classes,
Tasker and Task, which define a class to manage tasks and a task class
respectively.
'''
__author__ = 'Alex Bertsch'
__email__ = 'abertsch@dropbox.com'
from abc import ... |
import atheris
with atheris.instrument_imports():
import sys
import warnings
import mdformat
from mdformat._util import is_md_equal
# Suppress all warnings.
warnings.simplefilter("ignore")
def test_one_input(input_bytes: bytes) -> None:
# We need a Unicode string, not bytes
fdp = atheris.Fu... |
"""
Harish
2020-05-14
"""
import rospy
from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import State, PositionTarget
import math
from mavros_msgs.srv import SetMode, CommandBool
from std_msgs.msg import String, Header
import subprocess
class OffboardControl:
""" Controller for PX4-UAV offboa... |
#!/usr/bin/env python
# Copyright 2016 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... |
# Copyright (c) 2019 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 Cython.Build import cythonize
import pkg_resources
from setuptools import setup, Extension
import os
import sys
here = os.path.dirname(os.path.abspath(__file__))
extensions = []
files = {
0: "_enc_proc",
1: "_utils",
2: "_table",
3: "_encrypt",
}
for i in range(4):
filename = files[i]
exte... |
#!/usr/bin/env python3
import os
import os.path
import traceback
import shutil
import face_recognition
import cv2
import pickle
# from tqdm.notebook import tqdm
from zipfile import ZipFile
import logging
import amp.utils
FR_TRAINED_MODEL_SUFFIX = ".frt"
# Train Face Recognition model with the provided training_phot... |
from typing import List, cast
import pytest
from faker import Faker
from pydantic import SecretStr
from pytest_mock import MockFixture
from overhave import OverhaveAuthorizationSettings
from overhave.authorization import (
DefaultAdminAuthorizationManager,
LDAPAdminAuthorizationManager,
LDAPAuthenticator,... |
from __future__ import division
import os
import sys
import numpy as np
import tensorflow as tf
from tensorflow.keras.optimizers import schedules, Adam
from tensorflow.python.keras.losses import SparseCategoricalCrossentropy
from tensorflow.python.keras.metrics import SparseCategoricalAccuracy
from facenet import FaceN... |
import random, string, itertools
def alphabets_generator():
alphabet = ['1', '2', '3','4' , '5', '6', '7', '8', '9', '0', '_']
for letter in range(97,123): #all letters except first alphabet
alphabet.append(chr(letter))
alphabet1 = [] #first letter alpha... |
"""Template tags for anchors app"""
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from django import template
from django.contrib.sites.models import Site
from django.utils.safestring import mark_safe
from django.utils.html i... |
from functools import wraps
from flask import jsonify,current_app
from flask import request
import jwt
# 对token进行解码可以使用pyJWT
# pyjwt : python 实现的 JSON Web Token:
def token_required(f):
'''
验证前端发来的token信息是否合法,如果不合法,返回错误信息,不支持被装饰的函数f
如果合法,执行被装饰的函数f
'''
@wraps(f)
def __verfy(*args,**kwargs):
... |
"""Tests for Incremental PCA."""
import numpy as np
import pytest
import warnings
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_allclose_dense_sparse
from numpy.testing import assert_array_equal
from sklear... |
"""
Script for running American Airlines scraper directly from command line.
**Requirements**:
- Selenium
- Geckodriver
- Firefox web browser
- bs4 (BeautifulSoup)
Default name for file with search queries -
'search_tasks.json'(default location - script directory).
'search_tasks.json'(and similar files) must have foll... |
from typing import Any, Iterable, List, Mapping, Optional, Set, Tuple, Union
from django.conf import settings
from django.db.models.query import QuerySet
from django.utils.translation import ugettext as _
from zerver.lib.bugdown import convert as bugdown_convert
from zerver.lib.request import JsonableError
from zerve... |
config = {
"interfaces": {
"google.ads.googleads.v5.services.ExtensionFeedItemService": {
"retry_codes": {
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"non_idempotent": []
},
"retry_params": {
"default": {
"initial_retry_del... |
# coding: utf-8
import pprint
import re
import six
class ShowResourceHistoryRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and t... |
#!/usr/bin/env python
#
#
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#
import os, re, sys, copy
from subprocess import Popen, PIPE
from elf_correlate import immFunc
from elf_file import elfFile
from addr_utils import callNodes,phyAddrP
import bench
import cplex
impor... |
from veggies import Veggies
class Onion(Veggies):
def __str__(self):
return 'Onion' |
#!/usr/bin/env python3
import glob
def katparser(katfile):
"""Trivial parser for KAT files
"""
length = msg = md = None
with open(katfile) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
key, value = lin... |
import boto
from boto.s3.connection import S3Connection
from datetime import timedelta, datetime
import os
import pyart
from matplotlib import pyplot as plt
import tempfile
import numpy as np
import cartopy
def _nearestDate(dates, pivot):
return min(dates, key=lambda x: abs(x - pivot))
def get_radar_from_aws(si... |
"""
Django settings for testappauto328_dev_23386 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
... |
# Copyright 2016 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 applica... |
import pytest
from helpers.cluster import ClickHouseCluster
import random
import string
import os
import time
from multiprocessing.dummy import Pool
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance('node', main_configs=['configs/enable_test_keeper.xml', 'configs/logs_conf.xml'], with_zookeeper=True)
f... |
# coding: utf-8
"""
OOXML Automation
This API helps users convert Excel and Powerpoint documents into rich, live dashboards and stories. # noqa: E501
The version of the OpenAPI document: 0.1.0-no-tags
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
from conftest import add_permissions, check_dictionary
from core import NewJSONEncoder, cache
from forums.models import ForumCategory
def test_category_from_pk(app, authed_client):
category = ForumCategory.from_pk(1)
assert category.name == 'Site'
assert category.description == 'General site discussion'
... |
import os
import importlib
import logging
def import_methodmeta_decorated_classes(globals_d, package_name):
"""Prepare a package namespace by importing all subclasses following PEP8
rules that have @takes decorated functions"""
def finder(package_fs_path, fname):
if fname.endswith(".py") and fname... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.