content stringlengths 5 1.05M |
|---|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
"""Base classes for every engine"""
import logging
import numpy as np
log = logging.getLogger(__name__)
class BackendWrapper(object):
instance = None
def __init__(self, instance):
self.instance = instance
def __getattr__(self, attr):
"""
Attributes/Func... |
from __future__ import print_function
# -*- coding: utf-8 -*-
# %run make_eddy_track_ROMS.py
"""
===========================================================================
This file is part of py-eddy-tracker.
py-eddy-tracker is free software: you can redistribute it and/or modify
it under the terms of the G... |
class DocumentSearchIndexPresenter:
def __init__(self, document):
self.document = document
def asdict(self):
if not self.document:
return {}
document_dict = {}
if self.document.title:
document_dict["title"] = [self.document.title]
if self.docume... |
# Copyright 2019 The Sonnet 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 applicable l... |
from django.urls import path
from TopStore.products.views import create_product, update_product, delete_product, details_product, all_products, \
filter_products, like_product, review_product
urlpatterns = [
path('create/', create_product, name='create product'),
path('update/<int:pk>', update_product, na... |
from django.conf import settings
from django.db import models
from django.views.generic import ListView, TemplateView
User = settings.AUTH_USER_MODEL
DISTRICT_LIST = [
("Gros Islet", "Gros Islet"),
("Castries", "Castries"),
("Soufriere", "Soufriere"),
("Vieux Fort", "Vieux Fort"),
]
# def get_qu... |
import argparse
from dotenv import dotenv_values
import json
import random
import sys
import urllib3
from reasons import Reasons
def main(to, amount, reason, hashtag, api_token):
body = {}
body["receiver_email"] = to
body["amount"] = amount
body["hashtag"] = hashtag
body["reason"] = reason
... |
# Copyright 2021 AI Redefined Inc. <dev+cogment@ai-r.com>
#
# 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 l... |
import logging
from datetime import datetime
from urllib.parse import parse_qs, urlparse
from requests.sessions import Session as RequestsSession
from nephthys import FilterLoggerAdapter, Log, RequestLogRecord
from nephthys.filters.requests import BodyTypeFilter
logger = logging.getLogger("requests_out")
DEFAULT_AL... |
import boto3
from troposphere import Template
from chaosimp.name_constants import *
from chaosimp.decorators import handle_exception
class CloudFormation:
def __init__(self):
self.cf_resource = boto3.resource('cloudformation')
self.cf_client = self.cf_resource.meta.client
@handle_exception
... |
import pickle
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_,
assert_allclose)
from refnx.analysis import Parameter, Model
def line(x, params, *args, **kwds):
p_arr = np.array(params)
return p_arr[0] + x * p_arr[1]
def line2(x, p):
r... |
import argparse
import colorsys
import math
import os
import random
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pyglet
import trimesh
from OpenGL.GL import GL_LINEAR_MIPMAP_LINEAR
from PIL import Image
from tqdm import tqdm
import pyrender
from archiver import Archiver, SceneData
... |
from pandalchemy.migration import add_column, delete_column
from pandalchemy.pandalchemy_utils import get_table, get_type, has_primary_key
from pandalchemy.pandalchemy_utils import add_primary_key, get_table, primary_key
def update_sql_with_df(df, name, engine, schema=None, index_is_key=True, key=None):
"""Drops ... |
from synapse.tests.common import *
import synapse.lib.mixins as s_mixins
class Foo: pass
class Bar: pass
class MixTest(SynTest):
def test_lib_mixins_basics(self):
s_mixins.addSynMixin('ut', 'synapse.tests.test_lib_mixins.Foo')
s_mixins.addSynMixin('ut', 'synapse.tests.test_lib_mixins.Baz', 'synap... |
from lolacli import __version__
def test_version():
assert __version__=='0.1.4' |
#!/usr/bin/env python
"""
preprocess_json_params.py: utility functions for json paramter preprocessing
(see set_cpp_param() and get_cpp_param() methods
in print_class_defn.hpp)
The "process_params_out" and "process_params_in" utilities are used to handle
interconv... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : math.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 02/17/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
import scipy
import scipy.signal
import numpy as np
def discount_cumsum(x, gamma):
"""Com... |
import logging
import os
from html import escape as html_escape
from shutil import make_archive
from shutil import rmtree
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler
from telegram import ChatAction
from telegram import ParseMode
from telegram.error import BadRequest
from telegram.er... |
import json
from django.http import HttpResponse
from haystack.query import SearchQuerySet
def autocomplete(request):
results = SearchQuerySet().autocomplete(name_auto=request.GET.get('term', ''))[:10]
return_results = []
for result in results:
return_results.append({'label': result.name_auto, 'id'... |
#!/usr/bin/env python3
import os
import argparse
filename = "../../alias"
filename = os.path.dirname(os.path.realpath(__file__)) + "/" + filename
description = """
New Script.
"""
def parse_args():
parser = argparse.ArgumentParser(description=description)
parser.add_argument("name", help="The name of the a... |
from .calculation import *
from .iou import *
|
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.connect('localhost', 8000)
#Next, log in to the server
server.login("karan.sheth@somaiya.edu", "toastsandwhich")
def sendConfirmationMail(number, receiver):
try:
message = """From: Schemio admin@schemio.io
Subject: ... |
#
# @lc app=leetcode id=69 lang=python3
#
# [69] Sqrt(x)
#
# https://leetcode.com/problems/sqrtx/description/
#
# algorithms
# Easy (34.89%)
# Likes: 1884
# Dislikes: 2286
# Total Accepted: 696.7K
# Total Submissions: 2M
# Testcase Example: '4'
#
# Given a non-negative integer x, compute and return the square ro... |
import pytest
from similarity import create_app, db
from similarity.config import TestingConfig
@pytest.fixture
def app():
def _app(config_class):
app = create_app(config_class)
app.test_request_context().push()
if config_class is TestingConfig:
# Always starting with an empt... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2017, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
""" Implements Ex... |
# Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel, and University of Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import os
import numpy as np
import pandapipes
import ... |
from nextcord.state import ConnectionState
from .id_converter import IDConverter
from .errors import UserNotFound
from nextcord.ext.abc import ContextBase
from nextcord.ext import commands
import nextcord
import re
class UserConverter(IDConverter[nextcord.User]):
"""Converts to a :class:`~nextcord.User`.
All... |
"""This path modification is intended to give context to the test suite and allow the import
of the package
"""
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import classifier
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import time
def timer(f):
def wrapper(*args, **kwargs):
t = time.time()
r = f(*args, **kwargs)
print("Время выполнения функции: %f сек." % (time.time() - t))
return r
return wrapper
if __name__ == '__ma... |
import os
import pytest
from pandas.api.types import is_string_dtype
from dae.variants.attributes import Role
from dae.pedigrees.family import FamiliesData
from dae.pedigrees.loader import FamiliesLoader
@pytest.mark.parametrize(
"pedigree",
[
("pedigree_A.ped"),
("pedigree_B.ped"),
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 th... |
import setuptools
attrs = {
"name": "pygraph",
"version": "0.0.1a",
"description": "Graph related algorithms and data structures in Python.",
"author": "KIodine",
"packages": setuptools.find_packages(),
"python_requires": ">=3.7",
}
# Use `pip install -e .` for develope install.
... |
import http
from typing import Any, Dict, Iterable, Mapping, Optional, Union
from django.http import (
HttpRequest,
HttpResponse,
HttpResponseRedirect,
StreamingHttpResponse,
)
from django.template.response import TemplateResponse
from .constants import TURBO_STREAM_MIME_TYPE, Action
from .renderers i... |
import sys
def solve(line):
e1 = line.split("=")
if e1[1] == "?":
return 0
e2 = e1[0].split("+")
if (len(e2) == 2):
return int(e2[0])+int(e2[1]) == int(e1[1])
e2 = e1[0].split("-")
return int(e2[0])-int(e2[1]) == int(e1[1])
cnt = 0
for line in sys.stdin:
if solve(line.stri... |
import os
import path
TYPE_DICT = {"setRealParameter" : "float",
"setStringParameter" : "string",
"setIntegerParameter" : "int",
"setBooleanParameter" : "bool",
"setRgbParameter" : "color",
"setStringParameterEnum" : "enum"
}
PARAM_TYPE = {... |
from math import pi
def peripheral(pulley_diam:float, pulley_rpm:float):
r"""Mean peripheral linear velocity of the v-belt.
Parameters
----------
pulley_diam : float
mean diameter of the pulley, [mm]
pulley_rpm : float
rotational speed of the pulley, [rpm]
Re... |
# _*_ coding: utf-8 _*_
__author__ = "joyce"
import logging
import time
import os
class Logger(object):
def __init__(self, logger, log_name):
now1 = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
log_path = os.getcwd() + '\\Logs'
if not os.path.isdir(log_path):
... |
# -*- coding: utf-8 -*-
from abc import *
# Broker 抽象クラス
class AbstractBroker(object):
__metaclass__ = ABCMeta
@abstractmethod
def execute(self):
""" 注文の実行 """
raise NotImplementedError()
@abstractmethod
def sell(self):
""" 新規売り注文 """
raise NotImplementedError()
... |
import json
import pickle
import time
import os
from collections import defaultdict
from copy import deepcopy
import numpy as np
import torch
import torch.utils.data as data
from tqdm import tqdm
import nltk
# import stanza
# stanza.download('en')
# nlp = stanza.Pipeline()
import config
PAD_TOKEN = "<PAD>"
UNK_TOKE... |
import os
import pytest
# TODO: Use mock network services
def test_gbfs_client():
from gbfs.const import package_tests_fixtures_dirpath
from gbfs.data.fetchers import LocalJSONFetcher
from gbfs.client import GBFSClient
c = GBFSClient(os.path.join(package_tests_fixtures_dirpath, 'gbfs.json'), 'en',
... |
import pytest
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
from foolbox.models import TensorFlowEagerModel
@pytest.mark.parametrize('num_classes', [10, 1000])
def test_eager_model(num_classes):
bounds = (0, 255)
channels = num_classes
def mean_brightness_net(images):
lo... |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_len = 0
counter = 0
for val in nums:
if val == 0:
counter = 0
else:
counter += 1
... |
__version__ = 0.784 |
import os
import collections
import yaml
import hashlib
import six
import copy
import simpleeval
import pprint
from simpleeval import EvalWithCompoundTypes
from collections import Iterable, MutableMapping, OrderedDict
from collections import OrderedDict as odict
from cryptography.fernet import Fernet
from .ee import y... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... |
from namex.resources.auto_analyse.issues import DesignationMismatchIssue
class BcDesignationMismatchIssue(DesignationMismatchIssue):
pass |
import unittest
import os
import re
import logging
import sys
import shutil
import hashlib
testroot = os.path.dirname(__file__) or '.'
sys.path.insert(0, os.path.abspath(os.path.join(testroot, os.path.pardir)))
from chiptools.core import cli
# Blackhole log messages from chiptools
logging.config.dictConfig({'version... |
# First import the library
import pyrealsense2 as rs
# Create a context object. This object owns the handles to all connected realsense devices
pipeline = rs.pipeline()
pipeline.start()
try:
while True:
# Create a pipeline object. This object configures the streaming camera and owns it's handle
fr... |
#!/usr/bin/env python
# From: http://people.ds.cam.ac.uk/mcj33/themagpi/The-MagPi-issue-29-en.pdf
from Tkinter import *
window = Tk()
window.title('GUI Tkinter 1')
window.geometry("300x250") # w x h
window.resizable(0,0)
#define labels
box1 = Label(window,text="Entry 1: ")
#place the label in the window object
box1.g... |
# -- coding: utf-8 --
from flask import Blueprint, render_template, request
import ibm_db_dbi as db
from config import DB_CONNECTION_STRING
from collections import OrderedDict
from datetime import datetime
import timezonefinder, pytz
from geopy.distance import geodesic
from util_functions import decdeg2dms_latitude, d... |
import glob
import sys
def set_args(line: str = ""):
if '"' in line:
raise NotImplementedError
args = [arg for arg in line.split(" ") if arg]
sys.argv = sys.argv[:1] + args
def read_data(path, **kwargs):
import pandas as pd
paths = glob.glob(path)
def read(path):
try:
... |
import hail as hl
from hail.expr.expressions import expr_array, expr_call, expr_int32
from hail.expr.functions import _func
from hail.typecheck import typecheck
@typecheck(lgt=expr_call, la=expr_array(expr_int32))
def lgt_to_gt(lgt, la):
"""Transform LGT into GT using local alleles array.
Parameters
----... |
# python - v2 or more
#
#
# version : 1.0.0 (initial version ${1.0.0})
# description : python v2 or more and cloud foundry PaaS.
# Note: It will only print first 100 service bindings only.
# modifications : 1.0.0 (5/29/2018) initial version.
#
# author : r2d2c3p0.
# dob ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import itertools
import torch
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1... |
"""Ex061 Refaça o Ex051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos
da progressão usando a estrutura while."""
p = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
termo = p
c = 1
while c <= 10:
print(f'{termo} → ', end='')
termo += razao
c += 1
print('Fim')
|
from os import getenv
from discord.ext.commands import Bot
BOT_TOKEN = getenv("BOT_TOKEN")
bot = Bot(
command_prefix=".",
case_insensitive=True,
max_messages=10_000
)
bot.load_extension("bot.cogs.cogs")
bot.run(BOT_TOKEN)
|
# Link : https://leetcode.com/problems/roman-to-integer/submissions/
# Approach :
# 1.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
values = {
"I" : 1 , "V" :5 , "X" : 10 , "L" : 50 , "C" : 100 ,
"D" : 500 , "M" :... |
from scrapy.http import FormRequest
from scrapy import Spider
from scrapy.selector import Selector
from functools import partial
from ..items import RecordItemLoader, UfItemLoader
from .contants import *
class CorreiosSpider(Spider):
name = 'correios'
start_urls = [
'http://www.buscacep.correios.com.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Interpolate given variable to tropopause height.
###############################################################################
testkw/diag_tropopause.py
Author: Katja Weigel (IUP, Uni Bremen, Germany)
ESA-CMUG project
################################################... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
"""
ResGatedGCN: Residual Gated Graph ConvNets
An Experimental Study of Neural Networks for Variable Graphs (Xavier Bresson and Thomas Laurent, ICLR 2018)
https://arxiv.org/pdf/1711.07553v2.pdf
"""
c... |
iperf_peers=[('h012', 'h009', '75M'), ('h004', 'h012', '75M'), ('h016', 'h015', '75M'), ('h010', 'h004', '75M'), ('h015', 'h001', '75M'), ('h002', 'h003', '75M'), ('h006', 'h005', '75M'), ('h009', 'h008', '75M'), ('h014', 'h007', '75M'), ('h008', 'h006', '75M'), ('h005', 'h001', '75M'), ('h007', 'h001', '75M'), ('h001'... |
from bs4 import BeautifulSoup
import cloudscraper
import os
from __main__ import NovelLinks,NovelTitles,ChapterLinks
os.system("color")
Scraper = cloudscraper.create_scraper()
def Search(Series_Name):
headers = {
"accept": "*/*",
"x-requested-with": "XMLHttpRequest",
"user-agent": "Mozilla/5.0 (X... |
"""Templatetags used to generate files
===================================
Various templatetags provided by DjangoFloor in the
`gen_dev_files` command.
"""
import logging
from django import template
from django.utils.safestring import mark_safe
from djangofloor.conf.providers import IniConfigProvider
from djangofl... |
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
p = Pool(5)
print p.map(f, [1, 2, 3])
|
from __future__ import unicode_literals
from django.test import TestCase
from future import standard_library
from model_bakery import baker
from cradmin_legacy.tests.viewhelpers.cradmin_viewhelpers_testapp.models import FilterTestModel
from cradmin_legacy.viewhelpers import listfilter
standard_library.install_aliase... |
from typing import List, Optional
from overrides import overrides
import sqlalchemy
from snowshu.adapters.target_adapters import BaseTargetAdapter
from snowshu.configs import DOCKER_REMOUNT_DIRECTORY
from snowshu.core.models import materializations as mz
from snowshu.core.models.attribute import Attribute
import snows... |
# parse data
with open("data.txt") as f:
data = [int(x) for x in f.read().split(",")]
# Using a dict to store the number of fishes which are in a certain day of the cycle.
fishes = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}
for f in data:
fishes[f] += 1
# Iterate over days
for day in range(18):
... |
# -*- coding: utf-8 -*-
# Copyright 2019 The GraphicsFuzz Project 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
# Generated by Django 2.0.8 on 2019-01-07 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("user", "0014_auto_20181204_1536"),
]
operations = [
migrations.AddField(
model_name="accessprofile",
name="slug",
... |
# !/usr/bin/python
# -*- coding:utf-8 -*-
"""
@Author : jingle1267
@Time : 2019-07-20 05:09
@desc: :
"""
import os
import md2xmind
def main():
# print('example main')
file_path = os.path.abspath(os.path.join(os.getcwd(), 'test2.md'))
md2xmind.start_trans_file(file_path, 'test2', 'test22')
with open(file_... |
#!/usr/bin/env python3 -tt
# -*- coding: UTF-8 -*-
from socket import socket, AF_INET, SOCK_DGRAM
import codecs
import argparse
from secistsploit.core.exploit import *
from secistsploit.core.tcp.tcp_client import TCPClient
class Exploit(TCPClient):
__info__ = {
"name": "python_reverse_udp",
"descr... |
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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 righ... |
import glob
import unittest
from os import path
import sounddevice as sd
import soundfile as sf
from mockito import any, mock, unstub, verify, when
from psychopy import core
from bcipy.helpers.stimuli import play_sound, soundfiles,\
random_rsvp_calibration_inq_gen, best_selection, best_case_rsvp_inq_gen
MOCK_FS =... |
#!/usr/bin/env python
# Copyright (c) 2016 The UUV Simulator 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... |
import json
from pystratis.core.types import Money
from pystratis.api.balances.requestmodels import *
def test_overamountatheightrequest():
data = {
'blockHeight': 1,
'amount': '5.00000000'
}
request_model = OverAmountAtHeightRequest(
block_height=1,
amount=Money(5)
)
... |
#!/usr/bin/python3
# COPYRIGHT 2021 BY EXTRAHOP NETWORKS, INC.
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
import json
import requests
import os
# Retrieves the IP address or hostname of the ExtraHop system from an environment variable.... |
from tests import template, john, eric, michael
def match_keys(data, valid, path):
data_keys = data.keys()
valid_keys = valid.keys()
extra_keys = data_keys - valid_keys
missing_keys = valid_keys - data_keys
print(extra_keys)
print(missing_keys)
if missing_keys or extra_keys:
is_... |
import click
import click_pathlib
from flask import Flask, render_template, redirect, url_for
import glob
from pathlib import Path
from covid_graphs.country import CountryReport, GraphType
from covid_graphs.heat_map import HeatMap
CURRENT_DIR = Path(__file__).parent
@click.command(help="COVID-19 web server")
@clic... |
from day9_input import puzzle_input
def normal(puzzle_text):
output = []
index = 0
while index < len(puzzle_text):
if puzzle_text[index] == '(':
right_index = puzzle_text.find(')', index)
num_chars, num_repeat = puzzle_text[index + 1:right_index].split('x')
num... |
import contextlib
from cube2protocol.cube_data_stream import CubeDataStream # type: ignore
from cipolla.game.client.client import Client
from cipolla.game.player.player import Player
from typing import Any, Iterator, List, Optional, Tuple, Union, Set, Dict, Iterable
class ClientCollection(object):
def __init__(s... |
import logging
from twisted.internet import interfaces, defer
from zope.interface import implements
log = logging.getLogger(__name__)
class StreamCreator(object):
"""Classes which derive from this class create a 'stream', which can be any
collection of associated blobs and associated metadata. These cla... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
from scipy.io import wavfile
import pyrubberband as pyrb
halfsine = lambda W: np.sin(np.pi*np.arange(W)/float(W))
def STFT(X, W, H, winfunc = None, useLibrosa = True):
"""
:param X: An Nx1 audio signal
:param W: A window size
... |
from __future__ import print_function
import logging
logging.basicConfig(level=logging.WARN)
from os import path
from tubing import sources, tubes, sinks
f = "{}/doc.txt.gz".format(path.dirname(path.abspath(__file__)))
apparatus = sources.File(f, "rb") \
| tubes.Gunzip() \
| tubes.Split() \
| tubes.JSONP... |
"""feature tests of generated artifacts"""
import pprint
import shutil
import tarfile
import tempfile
from hashlib import sha256
from pathlib import Path
# use the generally-documented invocation
LITE_ARGS = "jupyter", "lite"
def test_archive_input(a_lite_app_archive, the_npm_source_date_epoch):
"""validate some... |
# Generated by Django 2.0.5 on 2018-06-07 10:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('it_purchase_app', '0031_auto_20180607_1031'),
]
operations = [
migrations.RemoveField(
model_name='purchase',
name='created_... |
import string
if __name__ == "__main__":
string ="""dddd
aaaa
bbbb
cccc"""
newstr = ""
for line in string.splitlines():
if line.startswith("a"):
newstr += "hello\n"
else:
newstr += (line+'\n')
print(newstr)
newstr = newstr.rstrip()
print(newstr)
|
import os
import fnmatch
import subprocess
from glob import glob
from ftplib import FTP
from random import shuffle
from .utils import clean_microbe_name
NCBI_FTP = 'ftp.ncbi.nlm.nih.gov'
def get_ftp_args(file_type):
if file_type == 'fasta':
return "--exclude='*cds_from*' --exclude='*rna_from*' --includ... |
from typing import Optional
class ServerSentEvent:
def __init__(
self,
data: str,
*,
event: Optional[str]=None,
id: Optional[int]=None,
retry: Optional[int]=None,
) -> None:
self.data = data
self.event = event
sel... |
import unittest
import json
from app import create_app
from app.models.v2 import User
class CreateUserTestCase(unittest.TestCase):
"""This class represents the api test case"""
def setUp(self):
"""
Will be called before every test
"""
self.app = create_app('testing')
s... |
#!/usr/bin/env python
'''
Created on Aug 10, 2009
@author: bud
'''
import logging
import logging.handlers
import optparse
import os
import pwd
import sys
import atexit
import signal
import tornado
import subprocess
#
# Init singleton object holding reloadable config values
# Must be done in the very first place bec... |
import rtree
from typing import List
from shapely.wkb import dumps, loads
from shapely.geometry import MultiPolygon, Polygon
def pixelwise_vector_f1(gt: List[Polygon],
pred: List[Polygon],
v: bool=True):
"""
Measures pixelwise f1-score, but for vector represent... |
# encoding: utf-8
from django.core.exceptions import ValidationError
import re
ERROR_TOO_LONG = 'MAC address is too long'
mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$')
def validate_mac(mac):
if mac == ERROR_TOO_LONG:
raise ValidationError(ERROR_TOO_LONG)
elif mac == '00:00:00:00:00:00'... |
# import cucim
import cupy as cp
import numpy as np
import uarray as ua
from cucim.skimage import morphology as _cucim_morphology
from skimage import morphology
_implemented = {}
def _implements(skimage_func):
"""Decorator adds function to the dictionary of implemented functions"""
def inner(func):
... |
import frappe
def get_additional_filters_config(*args, **kwargs):
filters_config = {
"journal status": {
"label": "Status Equal",
"get_field": "accounting.filters.get_journal_entry_status_field",
"valid_for_fieldtypes": ["Select"],
"depends_on": "status",
}
}
return filters_config
@frappe.whitelis... |
from setuptools import setup
setup(
name="amzscraper",
version="1.0.0",
description="A helpful utility to scrape and email Amazon receipts.",
url="https://github.com/tobiasmcnulty/amzscraper",
author="Tobias McNulty",
author_email="tobias@caktusgroup.com",
license="MIT",
py_modules=["am... |
# -*- coding: utf-8 -*-
"""
Script to copy images to Wikimedia Commons, or to another wiki.
Syntax:
python imagetransfer.py pagename [-interwiki] [-targetLang:xx] -targetFamily:yy]
Arguments:
-interwiki Look for images in pages found through interwiki links.
-keepname Keep the filename and do not veri... |
from __future__ import annotations
import yaml
from importlib.resources import read_text
from ...config.configuration import Metric, MetricConfiguration
from ...config.junos import JunosMetricConfiguration
from ...devices import junosdevice
from .. import junos
from ..base import Collector
from . import base
class ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... |
class UnknownPathException(Exception):
pass
class ValidationFailedException(Exception):
pass
class InvalidDataException(Exception):
pass
class ValidationFailedException(Exception):
pass
class UnexpectedRetrievalException(Exception):
pass
class VCSADetailsNotFoundException(Exception):
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.