text stringlengths 2 999k |
|---|
"""
Replace Emph elements with Strikeout elements
"""
from panflute import *
def action(elem, doc):
if isinstance(elem, Emph):
return Strikeout(*elem.content)
def main(doc=None):
return run_filter(action, doc=doc)
if __name__ == '__main__':
main()
|
# 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 may ... |
# Global Imports
import json
from collections import defaultdict
# Metaparser
from genie.metaparser import MetaParser
# =============================================
# Collection for '/mgmt/tm/ltm/monitor/postgresql' resources
# =============================================
class LtmMonitorPostgresqlSchema(MetaPars... |
def get_shopify_context(request):
return request.session.get('shopify')
|
from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:8555")
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
|
#_*_coding:utf-8_*_
import datetime
import re
from django import template
from django.db.models import Sum
from crm import models
from django.utils.safestring import mark_safe
from django.urls import reverse as url_reverse
register = template.Library()
@register.simple_tag
def get_study_record_count(enroll_obj):
... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = [
"airbyte-cdk~=0.1",
]
TEST_REQUIREMENTS = [
"pytest~=6.1",
]
setup(
name="source_harvest",
description="Source implementation for Harvest.",
author="Airbyte",
autho... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-08 17:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... |
# coding: utf-8
from settings import DATABASE_FILE
import dbparser
import process
from itertools import islice
db = dbparser.open_database(DATABASE_FILE)
prots = {prot.name: prot.domains for prot in islice(dbparser.parse(db), 200000)}
domains = process.extract_domains(prots)
|
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.Qt import Qt
from pydynamo_brain.model import FullState, Tree, UIState, History
from pydynamo_brain.files import AutoSaver, loadState, saveState, checkIfChanged, importFromMatlab, exportToSWC, saveRemapWithMerge
from pydynamo_brain.util import moveInList
from pydyn... |
from __future__ import division
import torch
import math
import sys
import random
from PIL import Image
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import collections
import warnings
from torchvision.transforms import functional as F
if sys.version_info < (3, 3)... |
# -*- coding: utf-8 -*-
"""The Flaw application is a minimalist tool to enable rapid
development, even in the face of inevitable errors.
Flaw is a small WSGI application, itself built on Clastic, which
activates when the development server cannot start, due to a
SyntaxError, or other import-time error. Flaw displays t... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
"""Find trees on a property, make suggestions for new trees."""
import json
import os
import pprint
from glob import glob
import numpy as np
import requests
from scipy import misc
from skimage.io import imsave
from skimage.transform import resize
from tqdm import tqdm
pp = pprint.PrettyPrinter(indent=4)
class Human... |
# -*- coding: utf-8 -*-
"""
.. _tut-brainstorm-auditory:
====================================
Brainstorm auditory tutorial dataset
====================================
Here we compute the evoked from raw for the auditory Brainstorm
tutorial dataset. For comparison, see [1]_ and the associated
`brainstorm site <https:... |
#!/usr/bin/env python3
"""
Read GVF lines from stdin and write bed9+ lines to stdout
"""
import os,sys,re
import argparse
bed9Fields = ["chrom", "chromStart", "chromEnd", "name", "score", "strand", "thickStart",
"thickEnd", "itemRgb"]
# the following list of fields may not exist for every record in the input fi... |
from rest_framework import viewsets
from .models import ListModel
from . import serializers
from utils.page import MyPageNumberPagination
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from .filter import Filte... |
import boto3
import json
import os
import random
import time
TOPIC_NAME = os.environ['TOPIC_NAME']
SERVICE_NAME = os.environ['SERVICE_NAME']
SQS_CONTAINER_MAPPING_TABLE=os.environ['SQS_CONTAINER_MAPPING_TABLE']
sns = boto3.client('sns')
sqs_client = boto3.client('sqs')
dynamodb = boto3.client('dynamodb')
def lambda_... |
from Components.config import config, ConfigSubsection, ConfigYesNo, ConfigSelectionNumber, ConfigSelection
import json
import os.path
#######################################################
# Initialize Configuration
config.plugins.skipintro = ConfigSubsection()
default_title_pattern = "(.*?)\s-\s(S\d+)E(.+)\s-\s(.*... |
#-*- coding: utf-8 -*-
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='Configuration file')
arg_lists = []
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
def str2bool(v):
return v.lower() in ('true', '1')
# Data
data_a... |
import os
import argparse
import numpy as np
from PIL import Image
from rawls.rawls import Rawls
import json
import glob
import shutil
# TODO:check if required to update the extract_nsamples for rawls
def extract_nsamples(img_path):
image_extension = img_path.split('.')[-1]
if image_extension == 'png':
... |
# search.py
import numpy as np
import itertools
# score: a beam_size * num_vars matrix, represent current score
# n: max number of elements to select
# threshold: prune if score < best + threshold
def find_nbest(score, n, threshold=None):
num_vars = score.shape[1]
# print(score.shape)
score = score.flat... |
# 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, Mapping, Optional, Sequence, Union, overload
from .. import... |
import torch
import torch.nn as nn
import time,datetime
import torch.nn.functional as F
import numpy as np
class Histogram2D_wrap(nn.Module):
def __init__(self, bins=100, min=0, max=1, norm=True, cuda=False):
super(Histogram2D_wrap, self).__init__()
self.bins, self.min, self.max, self.norm=bins,min... |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
from keyword2cmdline import command, command_config
TRANSLATIONS = {
("Hello world", "hi.IN"): "नमस्ते दुनिया"}
@command_config
def exclamation(number=2,
sign="!",
use=True):
return (sign * number if use else "")
@command
def m... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
__author__ = 'curator'
import sys
import os
import argparse
import win32com
import glob
import subprocess
import gme
def run_importer(project, lib_root, acm_file):
""" Runs the component importer. Project should not be in a transaction. acm_files is a list of acm or xml
AVM component model f... |
# Copyright 2021 The T5 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 writi... |
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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 ... |
import tensorflow as tf
def update_symmetry_edge_features(node_features, edges, edge_features, message_fn):
"""
Pass messages between nodes and sum the incoming messages at each node.
Implements equation 1 and 2 in the paper, i.e. m_{.j}^t &= \\sum_{i \\in N(j)} f(h_i^{t-1}, h_j^{t-1})
: nodes_featur... |
### All the files quoted below are within the same
### folder this script is in Github.
#-----------------------------------------------------
# Example 1
#-----------------------------------------------------
f = open("example1.txt")
# this opens a text file that's in the same folder of
# where this python sc... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from os import path
import sys
import unittest
from unittest.case import TestCase
from atores import Ator, DESTRUIDO, ATIVO, Obstaculo, Porco, PassaroAmarelo, PassaroVermelho
project_dir = path.dirname(__file__)
project_dir = path.join('..')
sys.path.app... |
import sublime
import sys
import os
st_version = 2 if sys.version_info < (3,) else 3
if st_version == 3:
from .package_control import text, sys_path
installed_dir, _ = __name__.split('.')
package_path = os.path.join(sys_path.st_dir, 'Installed Packages', 'Package Control.sublime-package')
pc_pytho... |
import os
import argparse
import requests
import cv2
import numpy as np
import tldextract
import pytube
import hashlib
import tldextract
import pytube
import time
import base64
from PIL import Image
from flask import Flask, request, render_template, redirect, make_response, jsonify
from pathlib import Path
from werkze... |
# Copyright 2018 Google LLC.
#
# 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 list of conditions and the following disclaimer.
#
#... |
# from __future__ import (
# annotations,
# )
# import typing
# from typing import (
# Optional,
# )
# import sys
# sys.setrecursionlimit(1 << 20)
# import dataclasses
# T = typing.TypeVar('T')
# V = typing.TypeVar('V')
# @dataclasses.dataclass
# class Node(
# typing.Generic[T, V],
# ):
# size: int = 1
# ... |
"""
Various tests for synchronization primitives.
"""
import sys
import time
from _thread import start_new_thread, TIMEOUT_MAX
import threading
import unittest
import weakref
from test import support
def _wait():
# A crude wait/yield function not relying on synchronization primitives.
time.sleep(0.01)
clas... |
# -*- coding: utf-8 -*
# Copyright (c) 2016 Civic Knowledge. This file is licensed under the terms of the
# Revised BSD License, included in this distribution as LICENSE
"""
Exporter to convert a notebook into a Metatab package.
"""
import sys
import copy
import io
import json
import logging
import nbformat
import re... |
__author__ = 'rodney'
from hstphot import radec2xy
from astropy.io import fits as pyfits
import numpy as np
from PythonPhot.photfunctions import rdpsfmodel
from PythonPhot.photfunctions import addtoimarray
def addtofits(fitsin, fitsout, psfmodelfile, position, fluxscale,
coordsys='xy', verbose=False):
... |
import numpy as np
import os
import torch
from torch import nn, optim
import torch.utils.data as Data
from torch.nn import functional as F
from torch import distributions
class Denoise(nn.Module):
def __init__(self, n_filters, filter_sizes, spike_size):
super(Denoise, self).__init__()
f... |
import logging
import pytest
from click.testing import CliRunner
from mock import MagicMock
from mock import call as mock_call
import connexion
from conftest import FIXTURES_FOLDER
from connexion.cli import main
from connexion.exceptions import ResolverError
@pytest.fixture()
def mock_app_run(mock_get_function_from... |
"""
Django settings for restapi project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
#... |
import pytest
from flask import json
from elasticsearch import ElasticsearchException
from elasticsearch_dsl.exceptions import ElasticsearchDslException
from backend.service import ProductService
from backend.util.response.products_count import ProductsCountSchema
from backend.util.response.error import ErrorSchema
... |
import sqlite3
sql = "CREATE TABLE customers "\
+"(id INTEGER PRIMARY KEY AUTOINCREMENT,"\
+"first_name TEXT NOT NULL,"\
+"last_name TEXT NOT NULL,"\
+"zipcode INT NOT NULL,"\
+"price_paid REAL NOT NULL);"
def main():
conn = sqlite3.connect('database.sqlite')
try... |
"""
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... |
# -*- coding: utf-8 -*-
import json
import os
import re
import time
from numbers import Number
import requests
from .log import log
from .webtrader import NotLoginError, TradeError
from .webtrader import WebTrader
class XueQiuTrader(WebTrader):
config_path = os.path.dirname(__file__) + '/config/xq.json'
de... |
"""
DIRBS Core statsd configuration section parser.
Copyright (c) 2018-2021 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are m... |
from .. import jobs as maplejobs
from ..character.characterKernel import GearedCharacter as GChar
from ..character.characterKernel import Union, HyperStat
from ..kernel import core
from dpmModule.kernel import policy
from dpmModule.execution import rules
MDF = core.CharacterModifier
"""
Optimizer
parameter : by POST... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
"""glGet* auto-generation of output arrays (DO NOT EDIT, AUTOGENERATED)"""
try:
from OpenGL.raw.GL._lookupint import LookupInt as _L
except ImportError:
def _L(*args):
raise RuntimeError( "Need to define a lookupint for this api" )
_glget_size_mapping = _m = {}
# _m[0x8892] = TODO # GL_ARRAY_BUFFER
# _m... |
from importlib import import_module
from Model.util import log_message
class DataSourcesSQLite:
def __init__(self, profile_path: str):
self.sources = {}
source_names = []
# Create list of module names and handlers, that we need
source_names.append(["Model.EdgeModel.SQLite.cookie", ... |
"""
Django settings for Proyecto project.
Generated by 'django-admin startproject' using Django 2.2.5.
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/
"""
import os
f... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Screen(AutotoolsPackage):
"""Screen is a full-screen window manager that multiplexes a phy... |
import pytest
from mock import patch, call
import services.schema_service
@patch('services.schema_service.read_schema')
@patch('services.schema_service.enrich_template')
def test_enrich_workspace_template_enriches_with_workspace_defaults_and_aad(enrich_template_mock, read_schema_mock, basic_resource_template):
w... |
# function 'compute' is distributed and executed with arguments
# supplied with 'cluster.submit' below
def wordCounting(text):
import re
wordList = re.sub("[^\w]", " ", text).split()
return (len(wordList))
if __name__ == '__main__':
# executed on client only; variables created below, including modules... |
# Generated by Django 2.1.5 on 2019-03-26 11:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... |
import json
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import altair as alt
import pandas as pd
import pytest
import requests
from furl import furl
import datapane as dp
from datapane.client import config as c
from ..local.test_api import gen_report_complex_with_files, gen_repo... |
#
# https://www.algorithmist.com/index.php/Longest_Common_Subsequence
#
def lcs3(a, b):
# generate matrix of length of longest common subsequence for substrings of both words
lengths = [[0] * (len(b)+1) for _ in range(len(a)+1)]
for i, x in enumerate(a):
for j, y in enumerate(b):
if x =... |
import tensorflow as tf
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from backend.loss_metric_utils import nan_mask, identity
class ClassificationLoss(tf.keras.losses.Loss):
def __init__(self, config, name='classification_loss', **kwargs):
super().__init__(name=name, **kwargs)
... |
import math
def test(a):
if a == 3000:
return 1
total = 0
return math.sqrt(1+(a-1)*test(a+1))
if __name__ == '__main__':
print (test(2017)) |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Files and Directories Explorer"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
from __future__ im... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: urban@reciprocitylabs.com
from datetime import date
from os.path import abspath
from os.path import dirn... |
#
# @lc app=leetcode.cn id=269 lang=python3
#
# [269] alien-dictionary
#
None
# @lc code=end |
#!/usr/bin/env python
"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
import base64
import BaseHTTPServer
import datetime
import httplib
import re
import StringIO
import time
from lib.core.bigarray import BigArray
from lib.core.settings import VERS... |
from neuromllite import Network, Cell, Population, Synapse, RectangularRegion, RandomLayout
from neuromllite import Projection, RandomConnectivity, OneToOneConnector, Simulation, InputSource, Input
from neuromllite.NetworkGenerator import check_to_generate_or_run
import sys
def generate():
dt = 100 # ms, so 0.... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free S... |
#!/usr/bin/env python
# Copyright (c) 2007, Secure64 Software 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['pyparsing']
setup_requirements = ['... |
#
# Copyright 2014 Rackspace. 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 ap... |
"""
Copyright 2018 InfAI (CC SES)
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... |
"""
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
"""
from datetime import timedelta
from functools import partial
import inspect
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Type, Union
import numpy as np
from pandas._l... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper SDK
# Copyright 2022 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import collections
from typing import Dict
FieldType = collections.namedtuple('FieldType', ['name', 'value', ... |
centerX = 500/2
centerY = 500/2
leng = 350
angle = PI/4
weight = 1
counter = 0
class myline():
def render(self, centerX, centerY, angle):
x1 = centerX - cos(angle)*leng/2
y1 = centerY + sin(angle)*leng/2
x2 = centerX + cos(angle)*leng/2
y2 = centerY - sin(angle)*leng/2
... |
import unittest
from masonite.helpers import Dot, config
from config import database
class TestConfig(unittest.TestCase):
def setUp(self):
self.config = config
def test_config_can_get_value_from_file(self):
self.assertEqual(self.config('application.DEBUG'), True)
def test_config_can_... |
#!/usr/bin/env python
"""lldb-repro
lldb-repro is a utility to transparently capture and replay debugger sessions
through the command line driver. Its used to test the reproducers by running
the test suite twice.
During the first run, with 'capture' as its first argument, it captures a
reproducer for every lldb invoc... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, msmr.ch and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class DPAbstimmungAuswahl(Document):
pass
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.core.exceptions import ValidationError
import os
from .models import Company, Contact, SupplierPart
from .models import rename_company_image
from part.models import Part
from InvenTree.exchange import InvenT... |
import datetime
import logging
from pathlib import Path
from string import Template
from urllib.parse import urlparse
from great_expectations.core.batch import Batch, BatchMarkers
from great_expectations.core.util import nested_update
from great_expectations.data_context.types.base import ConcurrencyConfig
from great_... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, DateTimeField, PasswordField, validators, Form
class EventForm(Form):
title = StringField(u'Заголовок события')
description = TextAreaField(u'Описание события')
timestamp_begin = DateTimeField(u'Время начала события')
tim... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... |
"""Tests for our main k2a CLI module."""
from subprocess import PIPE, Popen as popen
from unittest import TestCase
from k2a import __version__ as VERSION
class TestHelp(TestCase):
def test_returns_usage_information(self):
output = popen(['k2a', '-h'], stdout=PIPE).communicate()[0]
self.assertTr... |
import os
import sys
sys.path.append(os.getcwd())
from main import db
if __name__ == '__main__':
db.create_all()
|
from typing import List
class Factory:
"""
The base class for all factories in the project.
All you need to do in a subclass is fill the `classes` dict with the classes to be instantiated.
"""
# TODO Add environment variable with paths to modules where to search for classes
classes = dict()... |
from datetime import datetime, timedelta
from pymongo.mongo_client import MongoClient
from secrets import MONGO
class BasicMongo:
@staticmethod
def get_last(db):
return db.logs.aggregate(
[
{'$sort': {'mac': 1, 'timestamp': 1}},
{
'$gro... |
import hmac
import uuid
import urllib
import hashlib
import httplib as http
from github3.repos.branch import Branch
from framework.exceptions import HTTPError
from addons.base.exceptions import HookError
from addons.github.api import GitHubClient
MESSAGE_BASE = 'via the Open Science Framework'
MESSAGES = {
'add'... |
# coding=utf8
import socket
import time
import math
url = 'xkcd.com'
def log_time(func):
def wrapper(*args, **kw):
start_time = time.time()
func(*args, **kw)
print(time.time() - start_time)
return wrapper
def blocking_way():
sock = socket.socket()
sock.connect((url, 80))
... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... |
import time
from flask import Flask, render_template, flash, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
DBUSER = 'marco'
DBPASS = 'foobarbaz'
DBHOST = 'db'
DBPORT = '5432'
DBNAME = 'testdb'
app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.confi... |
# coding: utf-8
"""
Instagram API
The Instagram Private API in OpenAPI specs.v3.0 # noqa: E501
OpenAPI spec version: 0.0.1
GitHub repo: https://github.com/instagrambot/instagram-api-toolkit
"""
from __future__ import absolute_import
import unittest
import private_instagram_sdk
from JsonObject.cls... |
#!/usr/bin/env python3
# Copyright 2017 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 ... |
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import pathlib
from pathlib import PosixPath
from unittest.mock import patch, mock_open, Mock, MagicMock
from aiohttp import web
import pytest
from foglamp.services.core import routes
from foglamp.services.core.api import s... |
import calendar
def friday(day):
date = day.split(".")
for i in range(len(date)):
date[i] = int(date[i])
temp1 = calendar.weekday(date[2],date[1],date[0])
if temp1 <= 4:
return 4-temp1
else:
return 11-temp1
if __name__ == '__main__':
print("Example:")
print(friday('2... |
#!/usr/bin/env python
NAME = 'Airlock (Phion/Ergon)'
def is_waf(self):
# This method of detection is old (though most reliable),
# so we check it first
if self.matchcookie(r'^AL[_-]?(SESS|LB)='):
return True
# Nowadays many sites running Airlock do not set cookies
# directly without au... |
from django.http import JsonResponse
from django.views import View
import django_tesseract.tesseract
class TesseractView(View):
def post(self, request, format=None):
file_obj = request.FILES.get('file', None)
if file_obj:
transcript = django_tesseract.tesseract.transcript(file_obj)
... |
# -*- coding: utf-8 -*-
from amplify.agent.common.context import context
from amplify.agent.data.eventd import INFO
from amplify.agent.collectors.abstract import AbstractMetaCollector
from amplify.agent.common.util import subp, host
from amplify.ext.phpfpm.util.ps import LS_CMD, LS_CMD_FREEBSD, LS_PARSER
from amplify.e... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.