content stringlengths 5 1.05M |
|---|
from .pipenv_setup_comp import compare_deps
from ._version import (__title__, __description__, __url__, __version__,
__author__, __author_email__, __license__)
__all__ = ["compare_deps", "__title__", "__description__", "__url__",
"__version__", "__author__", "__author_email__", "__lic... |
"""
@file: This file contains the database helper class that manages both 'users' and 'contacts' collections
@Note: Calling this with python will do nothing
"""
#------------------------------STANDARD DEPENDENCIES-----------------------------#
import json
import pickle, copyreg, ssl # for serializing User obje... |
# https://leetcode.com/problems/keyboard-row
import re
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
match_r1 = lambda w: bool(re.match("^[qwertyuiop]*$", w.lower()))
match_r2 = lambda w: bool(re.match("^[asdf... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object("app.config.Config")
db = SQLAlchemy(app) #database object
migrate = Migrate(app,db) #object responsible for tracking changes in DB
from app import routes, models |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Junko Tsuji
# This script generates bed files as final outputs of
# DNA methylation pipeline by taking a CX_report file
# generated from bismark_methylation_extractor.
from optparse import OptionParser
import sys, os.path, string
# RGB strings and inte... |
# -*- coding: utf-8 -*-
import random
from source.tree.heap import MinHeap, MaxHeap
# region INSERTION SORT
# 直接插入排序
def straight_insertion_sort(a, reverse=False):
"""
直接插入排序
基本操作:将一个记录插入到已排好序的有序表中,从而得到一个新的,记录数增加1的有序表。
:param a:
:param reverse:
:return:
"""
# 从无序表的第二条记录开始
for i i... |
# Generated by Django 2.2.13 on 2021-02-25 16:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("data_refinery_common", "0063_auto_20210212_1855"),
]
operations = [
migrations.AlterModelOptions(name="dataset", options={"base_manager_name": "obj... |
from django.conf.urls import url
from views import FakeImageView
from . import views
urlpatterns = [
url(r'^', FakeImageView.as_view(),name='index.html'),
#url(r'^tweet_json/', FakeJSONView.as_view(),name='tweet_json.html')
] |
#!/usr/bin/env python
import logging
import unittest
from decimal import Decimal
import pandas as pd
from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import QuantizationParams
from hummingbot.core.clock import (
Clock,
ClockMode
)
from hummingbot.core.data_type.common import TradeType
from ... |
class ClonedRepoExistedError(Exception):
"""Base class for other exceptions"""
pass
class BranchUpToDateException(Exception):
pass
class DefaultCommitToolException(Exception):
pass
class PotentialInfiniteLoopException(Exception):
pass |
import os
from pathlib import Path
output = Path(os.path.abspath(__file__)).parent.parent / "output"
|
# Copyright 2017 Spotify AB
#
# 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, softw... |
### list all installed fonts plus it's variations
for fontName in installedFonts():
variations = listFontVariations(fontName)
if variations:
print(fontName)
for axis_name, dimensions in variations.items():
print (axis_name, dimensions)
print ()
|
"""
Module for abstract serializer/unserializer base classes.
"""
from StringIO import StringIO
from django.core.serializers.base import SerializationError, DeserializationError
from django.core.exceptions import ObjectDoesNotExist
class Serializer(object):
"""
Abstract serializer base class.
"""
# ... |
import unittest
from validator import format
class TestFormat(unittest.TestCase):
def test_invalid_yaml(self):
invalid_yaml = """
key: value
- item#1
- item#2
"""
(parsed, err) = format.validate(invalid_yaml)
self.assertIsNone(parsed)
self.assertEq... |
# coding: utf-8
# # For Loops (2) - Looping through the items in a sequence
# In the last lesson we introduced the concept of a For loop and learnt how we can use them to repeat a section of code. We learnt how to write a For loop that repeats a piece of code a specific number of times using the <code>range()</code... |
from django.test import TestCase
from django.utils import timezone
from datetime import timedelta
from decimal import Decimal
from blackbook.models import Currency, CurrencyConversion
class CurrencyTest(TestCase):
def testString(self):
currency = Currency.objects.create(name="Test Currency", code="TEST"... |
import sys, string
import re
from ucscGb.gbData.ordereddict import OrderedDict
import collections
class RaStanza(OrderedDict):
'''
Holds an individual entry in the RaFile.
'''
@property
def name(self):
return self._name
def __init__(self, key=None, value=None):
OrderedDict.__i... |
import json
from parserutils.strings import camel_to_snake
from ..query.fields import RENDERER_ALIASES
from ..query.fields import DictField, ObjectField
from .geometry import Extent
def to_words(cls_instance_or_name, as_string=True):
if isinstance(cls_instance_or_name, type):
class_name = cls_instance... |
import sys
from typing import Optional, TextIO
from antlr4 import InputStream
from src.messages.message_lexer import message_lexer
class Lexer(message_lexer):
def __init__(self, key: str, inp: InputStream, output: TextIO = sys.stdout):
super().__init__(inp, output)
self._recent = None
self.... |
start_node = '0'
end_node = '8'
def a_star(start_node, end_node):
open_set = set(start_node)
closed_set = set()
g = {} # Store distance from start node.
parents = {} # Parents contain an adjacent map of all nodes.
# Distance of start node from itself is zero
g[start_node] = 0
parents[start_node] = start... |
import functools
import numpy as np
import jax
import jax.numpy as jnp
from jax import jit, vmap
from jax.ops import index, index_update
def get_ray_bundle(height, width, focal_length, tfrom_cam2world):
ii, jj = jnp.meshgrid(
jnp.arange(width, dtype=jnp.float32,),
jnp.arange(height, dtype=jnp.floa... |
# coding: utf-8
"""
Author:
Weichen Shen,wcshen1994@163.com
Reference:
[1] Feng Y, Lv F, Shen W, et al. Deep Session Interest Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1905.06482, 2019.(https://arxiv.org/abs/1905.06482)
"""
from collections import OrderedDict
from tensorflow.python.... |
import pandas as pd
from ....Trade.Strategy.Cta.DyST_TraceFocus import *
from ....Trade.Strategy.DyStockCtaBase import *
from ....Trade.DyStockStrategyBase import *
class DyStockDataFocusAnalysisUtility(object):
"""
热点分析工具类
这个类有点特别,会借助DyST_FocusTrace类
"""
class DummyCtaEngine:
def... |
from pathlib import Path
from six.moves.urllib.parse import urlunparse
from six.moves.urllib.error import HTTPError
from six.moves.urllib.request import urlretrieve
import logging
logger = logging.getLogger(__name__)
class HiRISE_URL(object):
"""Manage HiRISE URLs.
Provide a storage path as calculated from... |
#!/usr/bin/env python
class Cart:
def __init__(self):
self.id = None
self.capacity = None
self.payload = None
self.last_known_location = None
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.get('https://www.dan.me.uk/bgplookup')
count=6535#接着上一次继续跑的初值
while count<=64511:
browser.find_element_by_name('asn').clear()
browser.find_element_by_name('asn').send_keys(count)
... |
# hw06_03
import random
def makesentence():
subjects = ['Dog', 'Cat', 'Monkey', 'Pig', 'Fox']
verbs = ['walks', 'runs', 'jumps']
advs = ['slowly', 'quickly']
print('%s %s %s.' % (random.choice(subjects), random.choice(verbs), random.choice(advs)))
for i in range(5):
makesentence()
'''
Cat walk... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QThread, pyqtSignal
from handlers import APIHandler, LoadMusicHandler
from config import config
from vkapi import VKLightError
from utils import save_json, stat
class LoadMusic(QThread):
music = pyqtSignal(list)
error = pyqtSignal(str)
... |
# Programa onde 4 jogadores jogam um dado e tem resultados aleatórios.
# Guarda esses resultados em um dicionário em Python. No final, coloca esse dicionário em ordem, sabendo que o
# vencedor tirou o maior número no dado.
from random import randint
from time import sleep
from operator import itemgetter
jogo = {'joga... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .kafka_consumer import KafkaCheck
__all__ = ['__version__', 'KafkaCheck']
|
import os
from multiprocessing.managers import BaseManager, BaseProxy
import numpy as np
import tensorflow as tf
from tensorflow.python.training import session_run_hook
from tensorflow.python.training.basic_session_run_hooks import SessionRunArgs
from rank_based import Experience
class sync_expericence(Experience):... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-03-21 08:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0147_merge_20190314_1451'),
]
operations = [
migratio... |
""" A module for getting the class names for a dataset, in a single canonical order.
"""
import json
from folder import datasets_path
def get_class_data(dataset):
path = datasets_path / dataset / 'classes.json'
with path.open('r') as f:
class_data = json.load(f)
class_data.sort(key=lambda d:... |
from .tell_os import is_linux
if is_linux():
import Xlib
import Xlib.display
from contextlib import contextmanager
from typing import Optional
from .abstract_desktop_monitor import AbstractDesktopMonitor
@contextmanager
def window_obj(display, win_id):
"""Simplify dealing with BadW... |
from io import open
import requests
def test_scene():
image_data = open("scene.jpg", "rb").read()
response = requests.post(
"http://localhost:80/v1/vision/scene",
files={"image": image_data},
data={"api_key": "Mojohn1"},
).json()
assert response["success"] ==... |
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def Hist(dataset, xlabel, filename): #Log Trip Duration His
sns.set_style("darkgrid")
sns.distplot(dataset, kde=True, rug=False)
plt.legend()
plt.xlabel(xlabel)
plt.ylabel('Frequency')
plt.tight_layo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/30 下午12:10
# @Author : wook
# @File : db.py
import pymysql
db = pymysql.connect(host="localhost", user="root", passwd="123123", db="mysql", port=3306, charset="utf8") # 连接对象
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() ... |
import os
from flask import Flask
from flask_cors import CORS
from .extensions import db, bcrypt
from flask_socketio import SocketIO
from .models import users, messages
from .config import DevConfig, ProdConfig
socketio = SocketIO(cors_allowed_origins="*")
def create_app():
app = Flask(__name__)
app.config['... |
"""
Copyright 2020 The OneFlow 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 law or agr... |
#!/usr/bin/env python3
import os
import random
import sys
import string
import random
if len(sys.argv) < 2:
print(f'Usage: {sys.argv[0]} <target>')
sys.exit(1)
ip = sys.argv[1]
print("Hello! I am a little sploit. I could be written on any language, but "
"my author loves Python. Look at my source - it... |
"""
IMPORT STEP
"""
import re
import datetime
import time
import traceback
import sys
import json
from math import ceil
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext, Row
from pyspark.sql.types import *
from pyspark.sql.functions import lit, col, udf
def save_txt(document, path):
... |
"""Tests for calculator.py."""
__author__ = 'Boris Polyanskiy'
import unittest
from party_calc.calculator import Person, PartyCalculator
class TestPerson(unittest.TestCase):
def test_init(self) -> None:
person = Person('mr.White')
self.assertEqual(person.name, 'mr.White')
self.assertEqu... |
from django.db import models
# Create your models here.
class Permission(models.Model):
"""
权限表
"""
hide_type_choices = (
(1, 'FALSE'),
(2, 'TRUE'),
)
route_url = models.CharField(max_length=64, verbose_name="路由路径", unique=True)
route_name = models.CharField(max_length=32,... |
from flask import Flask
from config import app_config
from app.database import create_tables
from app.api.views.user_endpoints import user
from app.api.views.meetup_endpoints import meetup
from app.api.utils.errors import err, bad_request, internal_server_error, not_found, method_not_allowed
def create_app(config_name... |
import unittest
from camera_trap_classifier.data.importer import DatasetImporter
class ImportFromCSVSingleImageTester(unittest.TestCase):
""" Test Import from CSV """
def setUp(self):
path = './test/test_files/dataset_single_image_multi_species.csv'
source_type = 'csv'
params = {'path... |
#! /usr/bin/env python
#
# Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
... |
import os
import pdb
from django import forms
from django.conf import settings
from django.contrib.auth import forms as auth_forms
from django.contrib.auth import password_validation
from django.core.files.uploadedfile import UploadedFile
from django.forms.widgets import FileInput
from django.utils import timezone
fro... |
'''
作者:邱少一
功能:
1.0功能:模拟投掷一个骰子
2.0新增功能:模拟投掷两个骰子
3.0新增功能:可视化投掷两个骰子的结果
4.0新增功能:=======直方图可视化作图和统计工具:matplotlib
5.0新增功能:=======科学计算工具:numpy
版本:1.0
日期:2017/12/1
学习:1、随机数:random():0到1的数;uniform(a,b):a到b的随机浮点数;randint(a,b):a到b的随机数
choice(<list>):随机从list中取一个元素 ;shuffle(<list>):将列表中元素打乱,sample(<list>,k):从列表... |
job_list = [
"python3 exp_neurolisp.py -o -t suite --dump --path=./test_data/suite_data/",
"python3 exp_neurolisp.py -o -t unify_mem --mem_size=2000 --dump --path=./test_data/unify_data/mem_test/",
"python3 exp_neurolisp.py -o -t unify_mem --mem_size=2500 --dump --path=./test_data/unify_data/mem_test/",
... |
# Copyright (c) 2020 ING Bank N.V.
#
# 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
# Copyright 2004-present Facebook. All Rights Reserved.
import json
import unittest
from network_health_service.stats.fetch_stats import get_link_queries, get_node_queries
from network_health_service.stats.metrics import Metrics
class CreateQueryTests(unittest.TestCase):
def setUp(self) -... |
import pathlib
import os
from argparse import ArgumentParser
from e3372 import WebAPI, SMSHandler, SMS
config_dir = os.path.join(pathlib.Path.home(), '.e3372-sms-handler')
trusted_phone = ''
def sms_handler(sms: SMS, api: WebAPI):
global trusted_phone
print(f'from={sms.phone}, date={sms.date}, text={sms.t... |
# hex
<warning descr="Python version 2.6, 2.7, 3.4, 3.5 do not support underscores in numeric literals">0xCAFE_F00D</warning>
# oct
<warning descr="Python version 2.6, 2.7, 3.4, 3.5 do not support underscores in numeric literals">0o1_23</warning>
<error descr="Python version 3.6 does not support this syntax. It requir... |
#!/usr/bin/env python
"""
Generate framework agreement signature pages from supplier "about you"
information for suppliers who successfully applied to a framework.
Usage:
scripts/framework-applications/generate-framework-agreement-signature-pages.py
[-v...] [options]
<stage> <framework> <output_dir... |
# Generated by Django 2.2.3 on 2019-10-21 08:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('devices', '0001_initial'),
('users', '0001_initial'),
]
operations = [
migrations.AddField(
... |
import gevent
from gevent import wsgi
import test__pywsgi
from test__pywsgi import *
del TestHttps
test__pywsgi.server_implements_chunked = False
test__pywsgi.server_implements_pipeline = False
test__pywsgi.server_implements_100continue = False
TestCase.get_wsgi_module = lambda *args: wsgi
if __name__ == '__main__':... |
import nau7802py, time
myScale = nau7802py.NAU7802() # Create instance of the NAU7802 class
#
# Begin void setup() equivalent
#
print('Qwiic Scale Example')
if not myScale.begin():
print('Scale not detected. Please check wiring. Freezing...')
while True:
pass
print('Scale detected!')
#
# Begin voi... |
import unittest
# These can't be imported until the test_imported_enums_proto module has been built.
Status = None
MessageID = None
ExposesInternalEnumConstantsMessageinternal_enum = None
UsesImportedEnumsMessage = None
class ImportedEnumsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
gl... |
# Generated by Django 3.2.5 on 2021-07-17 13:11
import contest.models
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_... |
import logging
from contextlib import contextmanager, AbstractContextManager
from typing import Callable
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy.orm import Session, sessionmaker, scoped_session
logger = logging.getLogger(__name__)
@as_... |
from flask import Flask, render_template, redirect, session, request
import random
import datetime
app = Flask(__name__)
app.secret_key = "12345678asdfghjk"
@app.route('/')
def index():
if not 'gold' in session:
session['gold'] = 0
if not 'log' in session:
session['log'] = ["Thanks for joining the game!"]
retu... |
from django.apps import AppConfig
class PersonConfig(AppConfig):
name = 'person'
|
#
# Copyright 2017-2018 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... |
from hazma.decay import charged_pion, muon, neutral_pion
from hazma.field_theory_helper_functions.common_functions import minkowski_dot as MDot
from hazma.parameters import electron_mass as me
from hazma.parameters import muon_mass as mmu
from hazma.parameters import charged_pion_mass as mpi
from hazma.parameters imp... |
# -*- coding: utf-8 -*-
"""Test settings"""
import os
# Set your environment variables for testing or put values here
# user email or phone number
USER_LOGIN = os.getenv('VK_USER_LOGIN', '')
USER_PASSWORD = os.getenv('VK_USER_PASSWORD', '')
# aka API/Client ID
APP_ID = os.getenv('VK_APP_ID')
PHONE_NUMBER = os.getenv... |
import cost_funcs.info as info
import cost_funcs.standard as std
import pytest
def test_bounds_eggholder():
assert info.get_bounds(std.eggholder, 2)[0][0] == -512
def test_bounds_michal_dim():
for dim in range(10):
assert len(info.get_bounds(std.michal, dim)) == dim
def test_function_name_eggholde... |
import re
from django.core import exceptions as core_exceptions
from api.models import Contributor, ExtendedField, ProductType
from api.facility_type_processing_type import (
get_facility_and_processing_type,
)
def extract_int_range_value(value):
"""
Excel workbooks mat contain decimal values for number_o... |
import os
import json
from collections import namedtuple
import shutil
import pytest
import responses
from coincurve import PrivateKey
from requests.exceptions import ConnectionError
import common.receipts as receipts
from common.tools import compute_locator, is_compressed_pk
from common.appointment import Appointment... |
import requests
import json
def post_to_rapidapps(body):
url = "https://rapid-apps-2475.eu-gb.mybluemix.net/services/2984dcb289ef8da69bfdc2442546d334"
payload = {
"iduser":body['iduser'],
"firstname":body['firstname'],
"lastname":body['lastname'],
"height":body['height'],
... |
# BerylDB - A modular database.
# http://www.beryldb.com
#
# Copyright (C) 2021 Carlos F. Ferry <cferry@beryldb.com>
#
# This file is part of BerylDB. BerylDB is free software: you can
# redistribute it and/or modify it under the terms of the BSD License
# version 3.
#
# More information about our licensing can be fou... |
# Generated by Django 3.1.2 on 2021-02-09 12:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('mvp', '0016_notification_ratings'),
]
operations = [
migrations.CreateModel(
name='Hub_User',
... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
'''
创建一个SURF对象:
cv2.xfeatures2d.SURF_create(, hessianThreshold, nOctaves, nOctaveLayers, extended, upright)
hessianThreshold:默认100
nOctaves:金字塔组数默认4
nOctaveLayers:每组金子塔的层数默认3
extended:默认False,扩展描述符标志,False表示使用64个元素描述符。
upright:默认... |
# terrascript/provider/rancher/rancher2.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:25:37 UTC)
import terrascript
class rancher2(terrascript.Provider):
"""Terraform Rancher2 provider"""
__description__ = "Terraform Rancher2 provider"
__namespace__ = "rancher"
__name__ = "ranche... |
#!/usr/bin/env python
import rospy
import numpy as np
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import PoseStamped
from tf import TransformListener
from copy import deepcopy
class MapWhiteout:
def map_callback(self, map):
print("received map!")
self.map = map
if self.... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.feature_selection import SelectPercentile, f_classif
# http://scikit-learn.org/stable/modules/feature_selection.html
# #############################################################################
# Univariate feature s... |
#Enter a number and identify whether it is palindrome or not.
n=int(input("Enter a no.:"))
n1=n2=n
count=0
temp=0
ans=0
while n!=0:
n=n//10
count=count+1
#print("count=",count)
count=count-1
while n1!=0:
temp=n1%10
n1=n1//10
ans=ans+(10**count)*temp
count=count-1
#print("ans=... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
import os
from mock import Mock
from mock import patch
from tests.base_unittest import BaseUnitTest
from aceonrivergui.server.game_manager import GameManager
import aceonrivergui.server.message_manager as MM
class MessageManagerTest(BaseUnitTest):
def test_broadcast_config_update(self):
uuids = ["hoge",... |
import qt
import numpy as np
import os
import shutil
import sys
import progressbar
from constants import *
fsv = qt.instruments.create('FSV', 'RhodeSchwartz_FSV', address = FSV_ADDRESS)
## FSV parameters
center_frequency = 6018.416185*MHz
span = 2000*Hz
RBW = 10*Hz
numpoints = 501
ref_level = -70 #dB... |
"""
This script is used to develop a baseline policy using only the observed patient data via Behavior Cloning.
This baseline policy is then used to truncate and guide evaluation of policies learned using dBCQ. It should only need to be
run once for each unique cohort that one looks to learn a better treatment policy ... |
from twisted.internet.defer import inlineCallbacks
from zope.interface import implements
from vumi.dispatchers.base import BaseDispatchWorker
from vumi.middleware import MiddlewareStack
from vumi.tests.helpers import (
MessageHelper, PersistenceHelper, WorkerHelper, MessageDispatchHelper,
generate_proxies, IH... |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... |
from typing import Dict, List, Union
from icolos.core.containers.compound import Compound
from icolos.core.containers.perturbation_map import Edge
from icolos.core.workflow_steps.pmx.base import StepPMXBase
from pydantic import BaseModel
from icolos.utils.enums.program_parameters import (
GromacsEnum,
StepPMXEn... |
# Generated by Django 3.2.9 on 2022-02-06 17:56
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='pet',
name='explan... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Gabor
def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0):
# get half size
d = K_size // 2
# prepare kernel
gabor = np.zeros((K_size, K_size), dtype=np.float32)
# each value
for y in range(K_size):
for x in range(K_size)... |
from aoc21.days.day04 import Board, BoardScore
NUMBERS = [
7,
4,
9,
5,
11,
17,
23,
2,
0,
14,
21,
24,
10,
16,
13,
6,
25,
12,
22,
18,
20,
8,
19,
3,
26,
1,
]
BOARD = Board(
[
22,
13,
17,
... |
from maza.core.exploit.option import OptEncoder
from maza.core.exploit.payloads import (
GenericPayload,
Architectures,
BindTCPPayloadMixin,
)
from maza.modules.encoders.perl.base64 import Encoder
class Payload(BindTCPPayloadMixin, GenericPayload):
__info__ = {
"name": "Perl Bind TCP",
... |
"""
Flask-AntiJs
-------------
Flask-AntiJs is a Flask extension the protects endpoints against
'undefined' javascript values by checking the URL, query params and payloads
and return a 400 (Bad request) response.
"""
from setuptools import setup
version = "0.0.2"
setup(
name='Flask-AntiJs',
version=version,... |
import configparser
import json
import os
import subprocess
import sys
import requests
import betamax
from betamax_serializers.pretty_json import PrettyJSONSerializer
import pytest
ABS_PATH = os.path.abspath(os.path.dirname(__file__))
FIXTURES_PATH = ABS_PATH + '/fixtures'
CASSETTES_PATH = FIXTURES_PATH + '/cassett... |
"""
Solution to Compound Interest Calculator
"""
if __name__ == '__main__':
principal = input('Enter the Principal: ')
# type checking here
try:
principal = float(principal)
except ValueError:
print('Invalid principal Amount')
exit(0)
rate = input('Enter ... |
# encoding: utf-8
"""
Core properties part, corresponds to ``/docProps/core.xml`` part in package.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from datetime import datetime
from ..constants import CONTENT_TYPE as CT
from ..extendedprops import ExtendedProperties
fr... |
import pytest
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils import timezone
from vms import models
def test_approve(client_admin_factory, employee_factory):
"""
Approving an employee should save the approval information and mark
the employee as activ... |
class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
l = 1
r = sum(candies) // k
def numChildren(m: int) -> bool:
return sum(c // m for c in candies)
while l < r:
m = (l + r) // 2
if numChildren(m) < k:
r = m
else:
l = m + 1
retur... |
# Generated from grammar/Evans.g4 by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .EvansParser import EvansParser
else:
from EvansParser import EvansParser
# This class defines a complete listener for a parse tree produced by EvansParser.
class EvansListener(ParseTreeListe... |
from builtins import object
import logging
from twisted.internet import abstract
from twisted.internet.tcp import Server
from twisted.internet import address, fdesc
log = logging.getLogger(__name__)
# AcceptedSocket
class AcceptedSocket(object):
transport = Server
def __init__(self, skt, addr, factory, re... |
import unittest
from user import User
from credentials import Credentials
import pyperclip
class TestUser(unittest.TestCase):
"""
Test case that defines the behavior that should be evident in the user class
"""
new_user= User("Mary","Wanjiku","wanjiku254")
new_account_name= Credentials("Instagram","... |
symbols = []
exports = [{'type': 'function', 'name': '??$_Getvals@_W@?$time_get@DV?$istreambuf_iterator@DU?$char_traits@D@std@@@std@@@std@@IEAAX_WAEBV_Locinfo@1@@Z', 'address': '0x7ffb3bb2d310'}, {'type': 'function', 'name': '??$_Getvals@_W@?$time_get@GV?$istreambuf_iterator@GU?$char_traits@G@std@@@std@@@std@@IEAAX_WAE... |
#!/usr/bin/env python
# FormatTIFFRayonixESRF.py
# Copyright (C) 2011 Diamond Light Source, Graeme Winter
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
#
# Sub class of FormatTiffRayonix to deal with images who have beam centers
# specifie... |
from unittest.mock import Mock
import pytest
from sso.user import context_processors
@pytest.fixture
def request_with_next_user_authenticated(rf):
request = rf.get('/', {'next': 'http://www.example.com'})
request.user = Mock(is_authenticated=Mock(return_value=True))
return request
@pytest.fixture
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.