content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
__author__ = 'frank'
import unittest
from sharefun.models import User, Role, AnonymousUser
from sharefun.permissions import Permission
class UserModelTestCase(unittest.TestCase):
def test_password_setter(self):
u = User(password='cat')
self.assertTrue(u.password_hash is... |
# Modify the details of a playlist (name, public, collaborative)
import sys
import spotipy
import spotipy.util as util
if len(sys.argv) > 3:
username = sys.argv[1]
playlist_id = sys.argv[2]
name = sys.argv[3]
public = None
if len(sys.argv) > 4:
public = sys.argv[4].lower() == 'true'
... |
from flask import url_for
from lib.tests import ViewTestMixin, assert_status_with_message
from kanban_boards.blueprints.user.models import User
class TestDashboard(ViewTestMixin):
def test_dashboard_page(self):
""" Admin dashboard page renders successfully. """
self.login()
response = sel... |
import os
from conans import ConanFile, tools
class CrowConan(ConanFile):
name = "crow"
version = "master"
license = "<Put the package license here>"
author = "<Put your name here> <And your email here>"
url = "<Package recipe repository url here, for issues about the package>"
description = ... |
# !/usr/bin/python
#
# Convert the gps csv files to a rosbag
#
# To call:
#
# python gps_to_rosbag.py gps.csv gps.bag
#
import rosbag, rospy
from std_msgs.msg import Float64, UInt16
from sensor_msgs.msg import NavSatStatus, NavSatFix
import sys
import numpy as np
def main(args):
if len(sys.argv) < 2:
... |
import unittest
class Solution:
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = set()
stack = []
def dfs(i):
for i in range(i, len(nums)):
if not stack or nums[i] >= stack[-1]:
... |
#!/usr/bin/env python
# Given the blocks, generate edges
# import argparse
from common import *
import fileinput
from itertools import combinations
def getEdges(blockfile):
edges = set()
for line in skip_comments(blockfile):
line = line.split(';')[1]
line = sorted([int(v) for v in line.split(',')])
for e in co... |
import connexion
import logging
import os
import shutil
from ignition.boot.config import ApplicationProperties, ApiProperties
from ignition.boot.connexionutils import RequestBodyValidator
from ignition.service.config import ConfigParserService, ConfigurationProperties
from ignition.service.framework import ServiceRegis... |
from __future__ import division, print_function, absolute_import
import tflearn
from tflearn.layers.conv import global_max_pool
import numpy as np
import pdb
# Residual blocks
# 32 layers: n=5, 56 layers: n=9, 110 layers: n=18
n = 5
# Building Residual Network
def resnext_model(X, Y, testX, testY, n_epoch):
n_inpu... |
from library import ini, log
from library.lang import LangConfig, LangFormValidation
from library.validation import ip_validator, form_empty, form_valid
from functools import partial
from PyQt5 import uic
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
def _update_form(form):
""" Set the default ... |
"""
Python code snippets vol 38:
187-Rename files to Unix friendly
stevepython.wordpress.com
requirements: None
(1) Changes spaces to hyphens
(2) Makes lowercase (not a Unix requirement, just looks better ;)
source:
https://gist.github.com/igniteflow/1226919
"""
import os
path = os.getcwd()
filenames = os.listdir(p... |
import setup_path
import airsim
class Land:
def __init__(self, port):
self.port = port
def start(self):
client = airsim.MultirotorClient('',self.port)
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
print("lan... |
"""a collection of functions to process multi-neuron spike trains using pandas DataFrames"""
import numpy as np
import numba
import pandas as pd
ms_to_s = .001
class Sorting:
"""a way to sort indexable items. For example, for neurons in raster plots.
A sorting is just a map from a set of real indices (for ... |
import sys
import argparse
from pymatgen.core.structure import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, default='POSCAR',
help='path to input file')
parser.add_a... |
#Finds the unique triplets of 3 numbers
#Runs in n^2 + nlogn + n
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
if all(v == 0 for v in nums):
return [[0,0,0]]
dictionary = {}
for x in range(len(nums)):
... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.leveleditor.worldData.JungleTestIslandA
from pandac.PandaModules import Point3, VBase3
objectStruct = {'Locator Links': [['11575... |
class NotAvailablePlayersException(Exception):
pass
class IsNotInstanceOfPlayerClass(Exception):
pass
class IsNotInstanceOfBootClass(Exception):
pass
class MaxNumbersOfPlayersExceptions(Exception):
pass
class NoCardsInDeck(Exception):
pass
class IsNotInstanceOfDeckClass(Exception):
pass... |
""" Describe the procedure that must be called at initialization. """
__version__ = '0.1.0'
from rpy2.robjects import r
# All modules share this R instance, so it is a constant
_R = r
_R("library(ggplot2)")
|
import math
import os
from concurrent.futures import Future, ThreadPoolExecutor, as_completed, wait
from dataclasses import dataclass
from pathlib import Path
from typing import List, Literal, Sequence, Union
from google.cloud import storage as gcs
from tqdm import tqdm
from practipy.text import remove_prefix
"""
TO... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 6.2
# in conjunction with Tcl version 8.6
# Nov 13, 2021 07:51:58 PM CST platform: Windows NT
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ... |
# -*- coding:utf-8 -*-
"""
@author: RubanSeven
@project: MirrorMirror
"""
from .param import *
from imgaug.augmenters.blur import *
from PyQt5.QtWidgets import *
class AverageBlurWidget(QTreeWidgetItem):
def __init__(self, *__args):
super().__init__(*__args)
self.name = 'AverageBlur'
... |
import atexit
import inspect
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from six import string_types
from artemis.experiments.experiment_record import ExpStatusOptions, experiment_id_to_record_ids, load_experiment_record, \
get_all_record_ids, clear_exper... |
PROJECT_NAME = 'Kreylin'
PROJECT_VERSION = 'alpha_1.5'
PROJECT_ICON = './res/icon64.png'
BACKGROUND_COLOR = (31, 33, 37)
CIRCLE_COLOR = (253, 222, 89)
TEXT_COLOR = (222, 222, 222)
SKY_0_COLOR = 0, 7, 26
SKY_5_COLOR = 5, 21, 60
SKY_7_COLOR = 56, 179, 255
SKY_13_COLOR = 242, 250, 255
SKY_17_COLOR = 138, 193, 227
SKY_18... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import time
import pytest
import grpc
import polymetis_pb2
import polymetis_pb2_grpc
import numpy as np
from polysim import GrpcSimulationCl... |
"""Kostal Plenticore Inverter."""
import logging
import kostalplenticore
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_PASSWORD
import homeassistant.helpers.config_validation as cv
from homeassistant.help... |
# encoding: utf-8
#python3
"""
O objetivo desse arquivo é tornar mais automático o processo de formatação e
limpeza dos dados das provas simuladas pela FGV DIREITO RIO. Os arquivos de
raw/simulated precisam ter o mesmo formato que os arquivos em raw/official.
Esse processo não é totalmente automático, ainda será nece... |
import json
import pygame
import time
from client.game_over_screen import GameOverScreen
from common.GUI.button import Button
from common.game_logic import GameLogic
class GameScreen(pygame.Surface):
local_game = True
is_admin = False
started = False
game_over = False
last_tick = 0
tick_qu... |
from UnionFind import UnionFind
unionFind = UnionFind(5)
assert unionFind.components() == 5
unionFind.unify(0, 1)
assert unionFind.components() == 4
unionFind.unify(1, 0)
assert unionFind.components() == 4
unionFind.unify(1, 2)
assert unionFind.components() == 3
unionFind.unify(0, 2)
assert unionFind.components() == 3... |
import json
from pyteomics import mass
class Expert_system(object):
def __init__(self):
self.data = {}
self.masses = []
self.load_data()
self.parse_data()
def load_data(self):
with open('common_util/rules.json') as f:
self.data = json.load(f)
def parse... |
"""register_add_choice0.06
Revision ID: 0df97b0d7106
Revises: b40569b341ea
Create Date: 2021-03-15 11:03:07.828989
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0df97b0d7106'
down_revision = 'b40569b341ea'
branch_labels = None
depends_on = None
def upgrade... |
"""
@author syt123450 / https://github.com/syt123450
"""
import subprocess
import os
import shutil
from tf.pb2json.pb2json_conversion import convert
input_format_config = '--input_format=tf_frozen_model'
def preprocess_frozen_model(input_path, output_path, output_node_names):
print("Preprocessing tensorflow fr... |
'''
import stocklab
def random_simulate(date, days, dates_expr, ohlc_expr, sign_expr, stocks_expr=None, verbose=False):
dates_expr = dates_expr(date, days)
dates = stocklab.metaevaluate(dates_expr)
if not stocks_expr:
stocks_expr = stocklab.config['stocks_of_interest']
stocks = np.asarray(list... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
"""
Verify that node resolution works
"""
def test():
import pyre.calc
# set up the model
model = pyre.calc.model()
# set up an expression with an unresolved node
model["p... |
import consts
import requests
def fetch_kitchen_data_from_dh(port):
res = requests.get(f'http://{consts.DH_HOST}:{port}/restaurant_data')
json_ = res.json()
return json_['config']
|
# -*- coding:utf-8 -*-
version = '0.1'
author = 'Xavier Lesa <xavier@link-b.com>'
from .emailvalidation import EmailValidation, EmailValidationException
from .fields import EmailValidationField
|
import unittest
from helpers import ssh_client
from main.maincontroller import MainController
from tests.xroad_cp_edit_settings_file.edit_settings_file import test_edit_settings_file
class XroadEditSettingsFile(unittest.TestCase):
"""
CP_03 Edit Settings File
RIA URL: https://jira.ria.ee/browse/XTKB-205
... |
# -*- encoding: utf-8 -*-
'''
Current module: demo.usage_pcmfc_driver
Rough version history:
v1.0 Original version to use
********************************************************************
@AUTHOR: Administrator-Bruce Luo(罗科峰)
MAIL: lkf20031988@163.com
RCS: demo.usage_pcmfc_driver,... |
import socket
import pytest
from sai import SaiObjType
from ptf.testutils import simple_tcp_packet, send_packet, verify_packets, verify_packet, verify_no_packet_any, verify_no_packet, verify_any_packet_any_port
def test_l2_access_to_access_vlan(npu, dataplane):
vlan_id = "10"
macs = ['00:11:11:11:11:11', '00:... |
# Copyright (c) Anish Acharya.
# Licensed under the MIT License
import numpy as np
from .base_gar import GAR
class Krum(GAR):
def __init__(self, aggregation_config):
GAR.__init__(self, aggregation_config=aggregation_config)
def aggregate(self, G: np.ndarray) -> np.ndarray:
dist = self.get_kr... |
#!/usr/bin/env python
# Takes a (possibly partial) schedule and checks it for conflicts.
# Provided under the terms of the MIT License, as stated in LICENSE.txt.
from course_selection import Preferences, Schedule, read_combined_file, \
gencmp_conflict, cmp_to_key
from optparse import OptionParser
# Helper functions... |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import os
def index(request):
return HttpResponse('hello world');
def pid(request):
return HttpResponse(str(os.getpid()));
@csrf_exempt
def media(request):
if request.method == 'POST':
text = request.FILES['file'];
ret... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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... |
'''Tests for the ValidateHash object'''
from __future__ import absolute_import
import unittest
from nose.tools import assert_true, assert_false
from hashit.core.hash_data import HashData
from hashit.core.hash_type import HashType
from hashit.service.validate_hash import ValidateHash
from hashit.utils.data_encap impo... |
#---------------------------------------
#Since : 2019/04/10
#Update: 2022/01/14
# -*- coding: utf-8 -*-
#---------------------------------------
import numpy as np
from copy import deepcopy
import random
import math
from nn_dropout import NNetWrapper as nnet
from parameters import Parameters
from Othello_bitboard impo... |
"""
Fully Convolutional U-net (Autoencoder) architecture.
"""
from typing import Any
import torch
import torch.nn as nn
from torch.nn.modules import padding
def weights_init(m: Any) -> None:
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(0.0, 0.02)
elif cl... |
import random
import json
STEVILO_DOVOLJENIH_NAPAK = 9
PRAVILNA_CRKA = "+"
PONOVLJENA_CRKA = "O"
VEC_KOT_CRKA = ">"
POSEBEN_ZNAK = "#"
NAPACNA_CRKA = "-"
ZMAGA = "W"
PORAZ = "X"
ZACETEK = "S"
class Igra:
def __init__(self, geslo, crke=None):
self.geslo = geslo
if crke is None:
self.c... |
import cv2
from dlib_points import shape_to_np
def return_distances(detector, predictor):
outer_points = [[49, 59], [50, 58], [51, 57], [52, 56], [53, 55]]
d_outer = [0]*5
inner_points = [[61, 67], [62, 66], [63, 65]]
d_inner = [0]*3
cap = cv2.VideoCapture(0)
while(True):
ret, img = ca... |
"""
Author
Junho Kim
takis0112@gmail.com
""" |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-08-20 20:20
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations
from nokia import NokiaAuth
from nokiaapp.utils import get_setting
def migrate_to_oauth2(apps, schema_editor):
Noki... |
from selenium import webdriver
DIRECTORY = 'C:/Users/KIIT/Downloads/Github/Flipkart Price Tracker/reports'
BASE_URL = "https://www.flipkart.com/"
def get_firefox_web_driver(options):
return webdriver.Firefox(executable_path =r"C:/Users/KIIT/Downloads/Github/Flipkart Price Tracker/geckodriver.exe", firefox... |
"""Test the shoulder-list management command
"""
import logging
import nog.shoulder as shoulder
import tests.util.sample as sample
class TestShoulderList:
def test_1000(self, caplog):
caplog.set_level(logging.INFO)
shoulder.dump_shoulders()
sample.assert_match(caplog.text, 'list')
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/talent_v4beta1/proto/tenant_service.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.protobuf imp... |
# Date: 03/18/2018
# Author: Ethical-H4CK3R
# Description: Scrape a site
from re import sub
from const import USER_AGENT
from dryscrape import Session
from cookielib import LWPCookieJar
from mechanize import _http, Browser
class Scraper(object):
def __init__(self, url, js):
self.url = url
self.... |
import glob
import os
import shutil
from PIL import Image
MAX_WIDTH = 750
MAX_HEIGHT = 500
THUMB_EXT = "_thumb.jpg"
for folder in glob.glob("blog/20*"):
images = []
for ext in ["jpeg", "jpg", "png"]:
images += glob.glob(folder+"/*."+ext)
for image in images:
fileName = os.path.basena... |
# -*- coding: utf-8 -*-
'''
Used to manage the thorium register. The thorium register is where compound
values are stored and computed, such as averages etc.
.. versionadded:: Carbon
:depends: statistics PyPi module
'''
# import python libs
from __future__ import absolute_import
try:
import statistics
HAS_S... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Nat64(A10BaseClass):
""" :param prefix_list: {"minItems": 1, "items": {"type": "prefix"}, "uniqueItems": true, "array": [{"required": ["prefix-val"], "properties": {"vrid": {"description": "VRRP-A vrid (Specify ha VRRP-A vrid)", "format": "number",... |
# -*- coding: utf-8 -*-
"""
Copyright 2020 Julius Wallnöfer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
"""
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import json
import linear_... |
import kfp
def download(url, file_content: kfp.components.OutputPath(str)):
import requests
response = requests.get(url=url)
if response.status_code == 200:
with open(file_content, 'wb') as file_content:
file_content.write(response.content)
else:
raise RuntimeError(f'Down... |
def _on_section_define(table):
pass
db.define_table('section',
Field('title', 'string',
requires=IS_NOT_EMPTY(), label=T('Section Title')),
Field('journal', 'reference journal'),
on_define=_on_section_define,
format='%(title)s'... |
from django.shortcuts import render
from rest_framework import viewsets, status
from .models import Movie, Rating
from django.contrib.auth.models import User
from .serializers import MovieSerializer, RatingSerializer, UserSerializer
from rest_framework.response import Response
from rest_framework.decorators import acti... |
"""SNMP config test cases."""
import pickle
import hypothesis
import hypothesis.strategies as st
from snmp_fetch import SnmpConfig
@hypothesis.given(
retries=st.integers(min_value=-1, max_value=(2 ** 32) - 1), # type: ignore
timeout=st.integers(min_value=-1, max_value=(2 ** 32) - 1),
max_active_sessio... |
import unittest
from wasmtime import *
class TestLinker(unittest.TestCase):
def test_define(self):
store = Store()
linker = Linker(store)
linker.allow_shadowing = False
func = Func(store, FuncType([], []), lambda: None)
linker.define("", "a", func)
g = Global(sto... |
import ila
import ptxILA
import pickle
import Instruction_Format
instruction_format = Instruction_Format.InstructionFormat()
BAR_OPCODE = 71
class ptxTwoThreadsILA(object):
def __init__(self):
self.model = ila.Abstraction('ptxTwoThreads')
self.createStates()
def createStates(self):
s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# === About ============================================================================================================
"""
ioTextFile.py
Copyright © 2017 Yuto Mizutani.
This software is released under the MIT License.
Version: 1.0.0
TranslateAuthors: Yuto Mizutani
E-mai... |
# Copyright (c) 2015 OpenStack Foundation.
# 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 re... |
#!env/bin/python3
import subprocess
import argparse
from htmldom import htmldom
import difflib
import urllib.parse
import os
# force latin1 encoding.
class LatinHtmlDom(htmldom.HtmlDom):
def getEncoding(self, response):
return "iso-8859-1";
def MyURL(uri, path="", query=""):
theURI = urllib.parse.quot... |
# Generated by Django 3.2.6 on 2021-08-28 11:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Player',
fields=[
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .pipeline import PipelineFramework, ConcretePipeline
from .rank import rank_by_total_successors, rank_by_successors
from .task import Task
|
import boto3
import logging
import os
def lambda_handler(event, context):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
region = os.environ['AWS_REGION']
ec2 = boto3.client('ec2', region_name=region)
cidr_blocks = event['cidr_blocks']
tgw_route_table_id = event['tgw_route_table... |
# In this file we run the main algorithm that returns our tickers
# Import functions
from elimination_system import *
from rating_system import *
# Import libraries
import time
from selenium.webdriver.firefox.options import Options
# Set options for selenium driver
options = Options()
options.binary_location = "/App... |
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from flatblocks.views import edit
urlpatterns = [
url('^edit/(?P<pk>\d+)/$',
staff_member_required(edit),
name='flatblocks-edit'),
]
|
import sys
import unittest
from geetools.tests import image, ee_list, cloud_mask, indices, expressions,\
geometry, imagestrip
import argparse
# TODO: allow making more than 1 test at a time
tests = {'image': image,
'list': ee_list,
'cloud_mask': cloud_mask,
'indice... |
# Auto generated by 'inv collect-airflow'
from airfly._vendor.airflow.models.baseoperator import BaseOperator
class CloudDataTransferServiceCancelOperationOperator(BaseOperator):
operation_name: "str"
gcp_conn_id: "str"
api_version: "str"
google_impersonation_chain: "typing.Union[str, typing.Sequence[... |
"""
Data IO api
"""
# flake8: noqa
from pandas.io.clipboards import read_clipboard
from pandas.io.excel import ExcelFile, ExcelWriter, read_excel
from pandas.io.feather_format import read_feather
from pandas.io.gbq import read_gbq
from pandas.io.html import read_html
from pandas.io.json import read_json
from pandas.i... |
file1 = open('input_8.txt', 'r')
Lines = file1.readlines()
bingo_numbers = Lines[0].split(",")
bingo_tables = []
bingo_tables_all = []
found_bingo = []
found_bingo_number = []
for line in Lines[2:]:
new_row = []
if line == '\n':
bingo_tables_all.append(bingo_tables)
bingo_tables = []
co... |
#!/usr/bin/env python3
from hermes_python.hermes import Hermes
from overhead import Aircraft, get_aircrafts
def make_speech_output(aircraft: Aircraft) -> str:
return '{}, {}.\n{}. Heading {}.\nFrom "{}", to "{}".'.format(
aircraft.airline,
" ".join(aircraft.flight_no[2:]),
aircraft.model_s... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-10-04 20:40:16
# Description:
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
@lru_cache(None)
def dp(i, j):
if i == -1 and j == -1: return True
return (j >= 0 and s2[j] ... |
import os
import sys
import codeop
import signal
import asyncio
import builtins
import traceback
try:
from ast import PyCF_ALLOW_TOP_LEVEL_AWAIT # Python 3.8+
except ImportError:
PyCF_ALLOW_TOP_LEVEL_AWAIT = 0 # Python 3.7-
try:
import readline
import rlcompleter
except ModuleNotFoundError:
readline... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from karrot.reporters.prometheus.models import PrometheusReporter
from karrot.reporters.cloudwatch.models import CloudwatchReporter
from karrot.reporters.stdout.models import StdoutReporter
class ReporterFactory(object):
"""
ReporterFactory used to create a Repor... |
import cv2
import numpy as np
import os
'''
Given images of individual growth modules, extract images of constituent plants
'''
MINIMUM_LEAF_SIZE = 12000
OFFSET = 20
THRESH_LOWER = np.array([25, 0, 40], np.uint8)
THRESH_UPPER = np.array([55, 230, 100], np.uint8)
REMOVE_INVADING_MATERIAL = False
plant_count = 0
de... |
from collections import OrderedDict
from rest_framework.authentication import BaseAuthentication
from ...oauth2_backends import get_oauthlib_core
class OAuth2Authentication(BaseAuthentication):
"""
OAuth 2 authentication backend using `django-oauth-toolkit`
"""
www_authenticate_realm = "api"
d... |
import numpy as np
from matplotlib.patches import Rectangle
def draw_patch(ax, node, **kwargs):
i, j = node
patch = Rectangle((j + 0.1, i + 0.1), 0.8, 0.8, **kwargs)
ax.add_patch(patch)
def draw_labyrinth(ax, L, start, end, n, m, **kwargs):
draw_patch(ax, start, facecolor='g', zorder=100)
draw_pat... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Submits JSON to a specified log within an InsightOps Logset"
class Input:
DATA = "data"
LOGSET_CONTAINER_ID = "logset_container_id"
class Output:
SUCCESS = "success"
class SubmitLogDataInput... |
# -*- coding: utf-8 -*-
from openprocurement.tender.core.utils import optendersresource
from openprocurement.tender.core.views.criterion_rg_requirement_evidence import (
BaseTenderCriteriaRGRequirementEvidenceResource,
)
from openprocurement.tender.core.validation import (
validate_eligible_evidence_data,
v... |
"""
Name: ans_recursive.py
Description: Calculates in how many ways can a given value be realized
with the use of an infinite number of coins of given values.
Options: None
Created on: 27.12.2017
Last modified: 23.10.2019
Author: Adam Graliński (adam@gralin.ski)
License: ... |
# -*- coding: utf-8 -*-
import clr
import rpw
from rpw.ui.forms import Button, ComboBox, FlexForm, CheckBox, Label, TextBox, Separator
from rpw import doc
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import (Outline, BoundingBoxIntersectsFilter, JoinGeometryUtils,
... |
import unittest
import numpy
from chainer import backend
from chainer.backends import cuda
from chainer import dataset
from chainer import testing
from chainer.testing import attr
class TestConcatExamples(unittest.TestCase):
def get_arrays_to_concat(self, xp):
return [xp.random.rand(2, 3) for _ in rang... |
# coding: UTF-8
"""
iinew.py
Copyright 2009-2010 Matthieu Nué
This file is part of InterInk.
#
# InterInk is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... |
__author__ = "Jwely"
__all__ = ["raster_fig"]
# standard imports
import matplotlib.pyplot as plt
class raster_fig:
"""
raster_fig objects are used for heads up displays of raster
data to the user.
:param numpy_rast: a numpy array representing araster dataset
:param title: title to put on... |
import sys
from g_python.gextension import Extension
from g_python.hunitytools import UnityRoomUsers
#from g_python.htools import RoomFurni, RoomUsers
extension_info = {
"title": "Room stuff",
"description": "g_python test",
"version": "1.2",
"author": "sirjonasxx & Hellsin6"
}
ext = Extension(extens... |
#!/usr/bin/env python3
import sys
import mastodon
import misskey
import pleroma
import shared
if __name__ == '__main__':
# Usage: ./fediscrape.py https://example.com/@user
if (
len(sys.argv) != 2 or sys.argv[1].count('@') != 1 or
sys.argv[1][0] == '@' or sys.argv[1][-1] == '@'
):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
thesis analysis
"""
from bs4 import BeautifulSoup
import requests
import sqlite3
import os
import re
# main_url = 'https://www.x-mol.com/paper/search/q?option='
main_url = 'https://scholar.google.com/scholar?hl=zh-CN&as_sdt=0,5'
# as_sdt=0,5 # 0,5不包含专利200... |
#!/usr/bin/python
#
# Copyright (c) 2016-2017 Nest Labs, 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/... |
from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION[:2] < (1, 11):
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
reverse = reverse
|
"""
This module is a collection of functions changing the automatic cache connection
system provided by maya. It's wrap aronud the mel command: doCreateNclothCache
By default maya allow the possibility to write cache for different node in a
single file. But this case is a nightmare to manage. So the manager force
a nc... |
# import urllib.request,json
# from .models import Quote
# quote_url = None
# def configure_request(app):
# '''
# function assigns quote_url the url value defined in config.py
# '''
# global quote_url
# quote_url=app.config['QUOTE_URL']
# def get_quote():
# '''
# function uses the pr... |
#!/usr/bin/python
import sys, argparse, re
from Bio.Format.Sam import SamStream
from subprocess import Popen, PIPE
from multiprocessing import cpu_count
def main():
parser = argparse.ArgumentParser(description="",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('input',help="Use bam file... |
from typing import Optional
from discord import Embed, Color
from datetime import datetime
from asyncio import sleep as _sleep
from traceback import format_exc
from discord.ext import commands
class OwnerCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=Tru... |
# Copyright 2021 The Chromium 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 unittest
from export_dtrace import DTraceParser
class DTraceReadTest(unittest.TestCase):
def testEmpty(self):
"""Tests that a directory with n... |
# -*- coding: utf-8 -*-
from .core import Service
from .models import User
class UserService(Service):
__model__ = User
user_service = UserService()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.