text stringlengths 1 927k |
|---|
import limits
import limits.storage
import limits.strategies
import ipaddress
class RateLimitExceeded(Exception):
pass
class Limiter:
def __init__(self):
self.storage = None
self.limiter = None
self.rate = None
self.subnet = None
self.rate_limit_subnet = True
def ... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.9.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized,
UnsupportedAlgorithm,
_Reasons,
)
cla... |
#!/usr/bin/python
#
# Copyright (c) 2011 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import... |
__all__ = ['Option', 'Configuration', 'option']
from typing import Type, FrozenSet, Dict, Any
import attr
import logging
from . import exceptions
logger = logging.getLogger(__name__) # type: logging.Logger
logger.setLevel(logging.DEBUG)
@attr.s(frozen=True)
class Option(object):
"""
Describes a configurat... |
import http.cookies
import threading
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusData
from hydrus.core import HydrusExceptions
from hydrus.core import HydrusGlobals as HG
from hydrus.core import HydrusPaths
from hydrus.core import HydrusSerialisable
from hydrus.core.networking import Hy... |
from batchq.core import batch
lsharp = 40
print ""
print "#"*lsharp
print "## 00 - a : Hello world"
print "#"*lsharp
class TestPipe1(object):
def hello_world(self):
print "Hello world"
class Q1(batch.BatchQ):
pipe = batch.Controller(TestPipe1)
fnc = batch.Function().hello_world()
instance = Q1()
p... |
import requests
from bs4 import BeautifulSoup
class HtmlUtil:
def __init__(self, url, skip_prep_price=False):
self.url = url
self._prepare_soup()
if not skip_prep_price:
self._prepare_price()
def _prepare_soup(self):
html = requests.get(self.url)
self.soup ... |
from __future__ import print_function, division
import os
import torch
from torch.autograd import Variable
from skimage import io
import pandas as pd
import numpy as np
from torch.utils.data import Dataset
from lib.transformation import AffineTnf
class PFPascalDataset(Dataset):
"""
Proposal Flow ... |
from rest_framework import serializers
from cms.api.serializers import UniCMSContentTypeClass, UniCMSCreateUpdateSerializer
from cms.medias.serializers import MediaSerializer
from . models import *
class ContactForeignKey(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
request = self.conte... |
# Copyright 2015 Google 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 required by applicable law or a... |
# system configuration generated and used by the sysconfig module
build_time_vars = {} |
import os
import zipfile
os.chdir("client") # Change directory to client
os.system('npm run build') # Building vue project
print("Build finished")
os.chdir("../server")
os.system("pip freeze > requirements.txt") # Creating requirements.txt
os.chdir("..")
# Creating zip archive with
zf = zipfile.ZipFile("build.z... |
"""
NOT FUNCTIONAL YET. DO NOT USE.
This module uses scipy's implementation of the L-BFGS-B optimization
method for searching through bounded search spaces.
Reference: https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html#optimize-minimize-lbfgsb"""
from scipy import optimize
from rekall.tuner imp... |
import json
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from django.urls import reverse
from django.contrib.auth import get_user_model
from .test_models import CreateArticle
from authors.apps.articles.models import Article
TEST_USER = {
"... |
#!/bin/python3
import sys
def countingSort(arr):
return sorted(arr)
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = countingSort(arr)
print (" ".join(map(str, result))) |
#!/usr/bin/env python
#-------------------------------------------------------------------------------------------------------
# Copyright (C) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
#---------------------------------------... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013, John McNamara, jmcnamara@cpan.org
#
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.TestC... |
from flow.controllers import IDMController, RLController
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.core.params import VehicleParams, SumoCarFollowingParams, SumoLaneChangeParams
from flow.envs import TestEnv
from flow.core.params import TrafficLightParams
from myscripts.nets... |
import pytest
from django.conf import settings
from django.test import RequestFactory
from newsapp.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> settings.AUTH_USER_MODEL:
return ... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--models-dir', metavar='PATH', default='./models/',
help='directory to save trained models, default=./models/')
parser.add_argument('--num-workers', metavar='N', type=int, default=4,
help='number of threads f... |
# The class representing the bicgstab iterative solver
from modules.model.labeling_module.Solvers.solver import Solver
from modules.model.labeling_module.ginkgo import Ginkgowrapper
import numpy as np
class BicgstabSolver(Solver):
# calculate the time it takes to solve the System Ax=b by calling the function in... |
# Simple Linear Regression
# Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Importing the dataset
dataset = pd.read_csv('../datasets/Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y... |
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
from datetime import timedelta
from graphql_jwt import exceptions, utils
from graphql_jwt.settings import jwt_settings
from .compat import mock
from .decorators import override_jwt_settings
from .testcases import TestCase
class JWTPayloadTests(TestCase):
@mock.patch('django.contrib.auth.models.User.get_usernam... |
"""Module for GraphQL schema and related queries and types."""
import graphene
from .schema import Query
schema = graphene.Schema(query=Query) |
# coding: utf-8
"""
NiFi Rest Api
The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... |
import re
from typing import Union
from ..meta import bbmeta
from .utils import flt
from ..errors import InvalidOperation
@bbmeta(
description="Given two values computes a true or false value depending on the operator selected.",
inputs=[
dict(
name="op",
type="str",
description="The condition operator."... |
import os.path
import tempfile
import unittest
from unittest import mock
def rm(filename):
os.remove(filename)
class RmTestCase(unittest.TestCase):
@mock.patch('__main__.os')
def test_rm(self, mock_os):
rm('/tmp/tmpfile')
mock_os.remove.assert_called_with('/tmp/tmpfile')
if __name__ =... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Steps:
1. Given a CSV export of F_YL_LEARNER
2. Create a unique list of all IBM email addresses
3. Perform a lookup in the Bluepages API
4. Populate MongoDB with this information
5. Then create a DbViz insert file of the Bl... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import sys
sys.path.append('/var/www/skills-api')
activate_this = '/var/www/skills-api/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
from app.app import app as application |
# Source Generated with Decompyle++
# File: clip_control.pyc (Python 2.5)
from ableton.v2.base import listens, liveobj_valid, listenable_property
from ableton.v2.control_surface import CompoundComponent
from ableton.v2.control_surface.control import ToggleButtonControl
from pushbase.clip_control_component import conve... |
"""
Stochastic Integrate-and-Fire Neurons
=================================
Coupling Force Variation
------------------------
**Author**: Guilherme M. Toso
**Tittle**: sif_couple_var.py
**Project**: Semi-Supervised Learning Using Competition for Neurons' Synchronization
**Description**:
This script uses the In... |
# Author : John Tsang
# Date : December 7th, 2017
# Purpose : Implement the Diebold-Mariano Test (DM test) to compare
# forecast accuracy
# Input : 1) actual_lst: the list of actual values
# 2) pred1_lst : the first list of predicted values
# 3) pred2_lst : the second list of ... |
# Copyright 2015 0xc0170
#
# 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, soft... |
#!/usr/bin/env python3
import cv2
from .cyolo import *
import numpy as np
class BBox(np.ndarray):
def __new__(cls, x, y, w, h, prob, name):
cls.name = ""
cls.prob = 0
obj = np.asarray([x, y, w, h]).view(cls)
obj.x, obj.y, obj.w, obj.h = obj.view()
obj.name = name
o... |
from os import listdir
from os.path import join
from PIL import Image
import torch
import torch.nn as nn
from torch.utils.data.dataset import Dataset
from torchvision.transforms import Compose, RandomCrop, ToTensor, ToPILImage, CenterCrop, Resize, transforms
from utils.jpeg_layer import jpeg_compression_transform, sim... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, add_days, today, nowdate, cstr
from frappe.model.document import Do... |
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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.... |
#!/usr/bin/python
import sys, os
from glob import glob
from pprint import pprint
mydir = os.path.dirname(__file__) or "."
os.chdir(mydir + "/breakpad")
p = {
"darwin": "mac",
"linux2": "linux",
"win32": "windows",
}[sys.platform]
dirs = [
"third_party/libdisasm",
"client",
"client/" + p,
"client/" + p + "/h... |
# Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import copy
import logging
import numpy as np
import pandas as pd
from typing import Any, Callable, Dict, List, Optional, Union
from sklearn.utils import check_consistent_length
import warnings
from functools import wra... |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""MySQLProvider module"""
import json
import logging
import time
from mysqlserver import MySQL
from ops.framework import StoredState
from ops.relation import ProviderBase
logger = logging.getLogger(__name__)
class My... |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Output, Input, State
from dash.exceptions import PreventUpdate
from .dash_app import DashApp
from .viewsettings import refresh_rate_ms, REFRESH_RATE
def build_status_bar(dashapp):
layout = html.Div([
html... |
"""Fake MRP Apple TV for tests."""
import asyncio
import logging
from pyatv.mrp import (messages, protobuf, variant)
from tests.airplay.fake_airplay_device import (
FakeAirPlayDevice, AirPlayUseCases)
_LOGGER = logging.getLogger(__name__)
class FakeAppleTV(FakeAirPlayDevice, asyncio.Protocol):
"""Implement... |
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# coding: utf-8
# In[1]:
import numpy as np
import csv
import random
import math
import pandas as pd
# In[2]:
TrainingPercent = 80 # 80% of raw data
ValidationPercent = 10 # 10% of raw data
TestPercent = 10 #10% of raw data
IsSynthetic =False
def GenerateRawData(filePath, IsSynthetic):
dataMatrix = [... |
# Copyright 2020 The DDSP 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 agreed to in wri... |
# Copyright (c) 2020, Ahmed M. Alaa
# Licensed under the BSD 3-clause license (see LICENSE.txt)
# ---------------------------------------------------------
# Helper functions and utilities for deep learning models
# ---------------------------------------------------------
from __future__ import absolute_import, div... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... |
# from lsst.ip.isr import IsrCalib
from .eoCalibTable import EoCalibField, EoCalibTableSchema, EoCalibTable, EoCalibTableHandle
from .eoCalib import EoCalibSchema, EoCalib, RegisterEoCalibSchema
from .eoPlotUtils import EoPlotMethod, nullFigure
__all__ = ["EoGainStabilityAmpExpData",
"EoGainStabilityDetExp... |
#!/usr/bin/env python2
"""\
Create a web logos for sequences generated by the design pipeline.
Usage:
pull_into_place web_logo <workspace> <round> [options]
pull_into_place web_logo <directory> [options]
Options:
--output PATH, -o PATH
The path where the logo should be saved. The desired file fo... |
import os
from setuptools import setup
from setuptools import find_packages
version = '0.35.0.dev0'
# Remember to update local-oldest-requirements.txt when changing the minimum
# acme/certbot version.
install_requires = [
'acme>=0.31.0',
'certbot>=0.34.0',
'mock',
'setuptools',
'zope.interface',
... |
import json
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import PurePath
from typing import Dict, Any
import requests
from injector import inject
from requests import HTTPError, ReadTimeout
from core_get.catalog.download_status_interface import DownloadStatusInterface
from core_get.... |
from pip import main
from floodsystem.geo import *
def run():
print("\n")
print("Rivers with the greatest number of stations:")
print(rivers_by_station_number(stations, 9))
print("\n")
if __name__ == "__main__":
run() |
from django.conf import settings
from django.conf.urls import patterns, url
from quix.django.contact.views import ContactView
from django.views.generic import TemplateView
template_name = getattr(settings, 'CONTACT_SUCCESS_TEMPLATE', 'contact/success.html')
urlpatterns = patterns('',
url(r'^$', ContactView.as_vie... |
from django import forms
from django.conf import settings
from django.utils.translation import pgettext_lazy
from payments import PaymentStatus
from ..registration.forms import SignupForm
from .models import OrderNote, Payment
class PaymentMethodsForm(forms.Form):
method = forms.ChoiceField(
label=pgette... |
import sys
import re
class Router:
"""
This module provides a simple way to decide program action
based on the command line parameters. This is particularly
useful for scripts that will be called by the server,
as it allows simple processing of the URI.
The Router class is the main brain of the routing module.
... |
import numpy as np
"""
------------------------------------------------------------------------------------------------------------------------------------------------------
SVM2
-------------------------------------------------------------------------... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import datetime
import logging
import os
import time
import torch
import torch.distributed as dist
from tqdm import tqdm
from maskrcnn_benchmark.data import make_data_loader
from maskrcnn_benchmark.utils.comm import get_world_size, synchronize
fr... |
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def thumbnail(obj):
url, ext = obj.url.rsplit('.', 1)
if obj.subject_location:
x, y = obj.subject_location.split(',')
else:
x = 0
y = 0
return '%s_%s_%s_%s.%s' %... |
import datetime as dt
from flask import current_app
from polylogyx.db.database import db
class ConfigDomain:
def __init__(self, node, remote_addr):
self.node = node
self.remote_addr = remote_addr
def get_config(self):
current_app.logger.info(
"%s - %s checking in to ret... |
# Generated by Django 2.0.6 on 2018-06-14 15:36
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('replicas', '0003_update_latency_meta'),
('geonet', '0001_init... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ...pvtpy.black_oil import Pvt,Oil,Water,Gas
from scipy.optimize import root_scalar
from .inflow import OilInflow, GasInflow
from ...utils import intercept_curves
from typing import Union
## Incompressible pressure drop
def potential_energy_ch... |
#!/usr/bin/env python3
# Copyright 2020 The Chromium OS 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 sys
import unittest
class DummyCliUnittest(unittest.TestCase):
def testImportCrosFactory(self):
from cros.factory.cl... |
from typing import Optional
from thyme.types.blockchain_format.coin import Coin
from thyme.types.blockchain_format.program import Program
from thyme.types.blockchain_format.sized_bytes import bytes32
from thyme.wallet.puzzles.load_clvm import load_clvm
MOD = load_clvm("genesis-by-coin-id-with-0.clvm", package_or_requ... |
# -*- coding: utf-8 -*-
#
# Copyright 2021 Nitrokey Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://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 distribute... |
import json
from unittest import TestCase
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.stream.db.operation import add_records, select_all, select_all_input_output_pairs, get_inputs, \
get_misinfo, put_outputs, select_input_output_pairs_by_date, select_recent_input_outp... |
"""
MIT License
Copyright (c) 2020 Airbyte
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, distr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cnheider'
from collections import namedtuple
import numpy as np
class InitStateDistribution(object):
StateDist = namedtuple('StateDist', ('state', 'prob'))
def __init__(self):
self.state_tuples = []
def add(self, state, prob):
self.state_t... |
import logging
import mdstat
from abackup.fs import DriveStatus, PoolState, PoolStatus, get_fs_stats
def pool_status(name: str, path: str, log: logging.Logger = None):
if log:
log.debug("pool_status({}, {})".format(name, path))
stats = get_fs_stats(path)
if log:
log.debug("pool_status({},... |
from ..api import APIWrapper
from typing import Tuple, Dict, Any
class ProxmoxUser:
def __init__(self, api: APIWrapper, userid: str):
self._api = api
self._userid = userid
self._fulluserid = userid + "@pve"
@property
def id(self) -> str:
"""
:return: Unique ID of u... |
# Testing Setup of Multilayer Extraction
import networkx as nx
import pandas as pd
import numpy as np
import math
import itertools as it
from . import adjacency_to_edgelist
from . import expectation_CM
from . import initialization
from . import score
import matplotlib.pyplot as plt
# Gen default testing graph
g1 = nx.... |
from django import forms
from .models import ImgClass
class ImageForm(forms.Form):
image = forms.ImageField()
class Meta:
model = ImgClass
fields = {'img_path', 'img_classifier', 'photo'} |
import os
import pymongo
from dotenv import load_dotenv
load_dotenv()
DB_USER = os.getenv("MONGO_USER", default="OOPS")
DB_PASSWORD = os.getenv("MONGO_PASSWORD", default="OOPS")
CLUSTER_NAME = os.getenv("MONGO_CLUSTER_NAME", default="OOPS")
connection_uri = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{CLUSTER_NAME}.mo... |
'''Helper methods for making classification predictions.
'''
import numpy as np
def get_class(proba, labels):
'''Gets the class label from the specified class probability estimates.
Args:
proba (array like): The estimated class probability estimates.
labels (dictionary): The label dictionary... |
from collections import defaultdict
from scipy import spatial
import numpy as np
class MetricManager(object):
def __init__(self, metric_fns):
self.metric_fns = metric_fns
self.result_dict = defaultdict(float)
self.num_samples = 0
def __call__(self, prediction, ground_truth):
... |
from datetime import datetime
import time
MAX_PLAYERS_IN_GAME = 1000
class BaseFunctionBuilder():
def __init__(self, command_name):
self.command_name = command_name
def is_registered(self):
"""
Determines if function is already registered in redis database.
Makes a `RG... |
from django.urls import path
from django.contrib.auth import views as auth_views
from accounts.views import (
launch_page,
SignUpView,
ProfileDetail,
AccountUpdate,
UserDelete,
BeginPasswordChange,
PasswordResetView,
PasswordResetConfirm,
AccountPictureUpdate,
)
app_name = 'accounts... |
import gzip
import re
import os
import shutil
import sqlite3
from pathlib import Path
import scripts.artifacts.artGlobals
from packaging import version
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, logdevinfo, timeline, tsv, is_platform_windows
def get_powerlogGZ(file... |
# Copyright (c) 2015 Mirantis, 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 requir... |
from dnsquery import app
if __name__ == "__main__":
app.run() |
#!/usr/bin/env python3
"""Script to check whether the installation is done correctly."""
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import importlib
import logging
import sys
import traceback
from distutils.version import LooseVers... |
"""jase_im URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
n = 5
xy = [map(int, input().split()) for _ in range(n)]
sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy]))
b = (n * sxy - sx * sy) / (n * sx2 - sx ** 2)
a = (sy / n) - b * (sx / n)
x = 80
y = a + b * x
print(round(y, 3)) |
import queue
import copy
import json
import threading
from multiprocessing import Process
import couchbase.subdocument as SD
from membase.api.rest_client import RestConnection
from memcached.helper.data_helper import VBucketAwareMemcached
from lib.couchbase_helper.random_gen import RandomDataGenerator
from lib.couchb... |
# The MIT License
#
# Copyright (c) 2011 Wyss Institute at Harvard University
#
# 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
# ... |
import os
from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from dotenv import load_dotenv
load_dotenv()
apikey = os.environ['apikey']
url = os.environ['url']
authenticator = IAMAuthenticator(apikey)
language_translator = LanguageTranslatorV3(
version... |
# Lint as: python2, python3
# 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
#
... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Compare two or more pigeonds to each other.
To use, create a class that implements get_tests(), and pa... |
import nltk
from nltk.corpus import wordnet as wn
import string
from nltk.corpus import stopwords
def get_WordNet_augmentation(word):
# Given a word, returns a list of hypernyms, synonyms, meronyms, and troponyms (not found in wordnet)
stops = set(stopwords.words("english"))
syns = wn.synsets(word)
ret... |
# ---------------------------------------------------------------------
# Building object
# ---------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python modules
... |
# Copyright (c) 2016, The Bifrost Authors. All rights reserved.
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must re... |
# Code source https://gitee.com/weidongshan/pico-micropython/tree/master/pwm
# Example using PWM to fade an LED.
import time
from machine import Pin, PWM
# Construct PWM object, with LED on Pin(25).
pwm = PWM(Pin(0))
# Set the PWM frequency.
pwm.freq(1000)
# Fade the LED in and out a few times.
duty = 0
direction ... |
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE
import logging
logger = logging.getLogger(__name__)
logger.propagate = True # passes up to parent logger
def db_to_fna(db, collection, seqtype="CDS"):
"""Takes records of ``"type":seqtype` (like "CDS" or "16s"), writes them to file
Ar... |
# Dash app libraries
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import base64
from dash_extensions import Download
# Rep strat input descriptions
from inputD... |
"""Test cltk.tag."""
import os
import shutil
import unittest
from cltk.corpus.utils.importer import CorpusImporter
from cltk.stem.latin.j_v import JVReplacer
from cltk.tag import ner
from cltk.tag.ner import NamedEntityReplacer
from cltk.tag.pos import POSTag
__license__ = 'MIT License. See LICENSE.'
class TestSeq... |
#!/usr/bin/env python3
# Copyright (c) 2015-2019 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 a node with the -disablewallet option.
- Test that validateaddress RPC works when running with -d... |
import datetime
from sqlalchemy import (
Column, Datetime
)
from sqlalchemy.ext.declarative import declarative_base
class Base(object):
created_at = Column(
Datetime,
default=datetime.datetime.utcnow,
nullable=False
)
updated_at = Column(
Datetime,
default=date... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ykdl.simpleextractor import SimpleExtractor
from ykdl.util.html import get_content, add_header
from ykdl.util.match import match1, matchall
class ZYLive(SimpleExtractor):
name = u"ZhangYu Live (章鱼直播)"
def __init__(self):
SimpleExtractor.__init__(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.