text stringlengths 2 999k |
|---|
import random
import math
from typing import List, Dict
"""
This file can be a nice home for your move logic, and to write helper functions.
"""
def avoid_my_neck(my_head: Dict[str, int], my_body: List[dict],
possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates... |
# coding=utf-8
import re
import ast
from setuptools import setup, find_packages
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('XTestRunner/__init__.py', 'rb') as f:
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
setup(
name='XTestRunner',
v... |
"""Command line entry points.
"""
import argparse
from . import __version__
def hello():
""" Hello world sample entry point.
"""
print("hello world version {}".format(__version__))
def gdbye():
""" Goodbye sample entry point.
"""
print("Goodbye version {}".format(__version__))
|
from os import environ, path
from collections import namedtuple
from json import load
MySQLConfig = namedtuple('MySQLConfig', 'host port user password db')
AppConfig = namedtuple('AppConfig', 'host port')
def read_mysql_config():
return MySQLConfig(
host=environ['MSQL_HOST'],
port=int(environ['MS... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from collections import defaultdict
from django.contrib.gis import forms, gdal
from django.contrib.gis.db.models.lookups import (
RasterBandTransform, gis_lookups,
)
from django.contrib.gis.db.models.proxy import SpatialProxy
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geometry.... |
"""Exercise 2: Given that fruit is a string, what does fruit[:] mean?"""
# fruit[:] means all characters in the sequence fruit
|
# Copyright 2019-2021 Canaan Inc.
#
# 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 writ... |
"""Provide file operator functions."""
# Import built-in modules
import codecs
import json
# Import third-party modules
import yaml
def read_yaml(file_path):
"""Read a YAML file by the given path.
Args:
file_path (str): The absolute path of the YAML file.
Returns:
dict: The data spec_r... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Camptocamp SA
# All rights reserved.
# 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
# l... |
class Solution:
# Time complexity: O(n) where n the length of pushed is
# Space complexity: O(n)
def validateStackSequences(self, pushed, popped):
j = 0
stack = []
for x in pushed:
stack.append(x)
while stack and j < len(popped) and stack[-1] == popped[j]:
... |
from .data import Data
def tango(req):
words = Data.get_list()
words = list(map(lambda x: x['kanji'], words))
return ', '.join(words)
def hello_world(req):
return 'Hello, world!'
|
import os
import math
import pickle
import random
import numpy as np
import lmdb
import torch
import cv2
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP']
####################
# Files & IO
####################
def is_image_file(filename):
return any(filename.end... |
from flask import Flask, jsonify
import stripe
import os
app = Flask(__name__)
stripe.api_key = os.environ.get('STRIPE_SK_TEST')
stripe.api_version = '2020-08-27'
# Set your secret key. Remember to switch to your live secret key in production.
# See your keys here: https://dashboard.stripe.com/apikeys
customer = stri... |
from sast.exceptions import *
from sast.expressions import *
from sast.expressions import _list
import sast.builtins as builtins
class SastEnv(SastDict):
pass
Env = SastEnv()
Env.Set(Cons, builtins.New("SastCons", env=Env, call=builtins.Cons))
Env.Set(List, builtins.New("SastList", env=Env, call=built... |
from Crypto.Util.number import bytes_to_long
n = 7354261656064787756554403678873802520293938142515873772154439835685178740118351616322183701392955956899384404680418797770537628910806512688360356290494174865360783635826735966404106470876215447478616820462818166737130578830362439690332321627911068539914547691658512291... |
"""
Plugin for Transmission torrent client.
Requires Transmission install: sudo apt-get install transmission-daemon
You'll probably also want the command-line client: transmission-cli so you can add and manage torrents.
Auth isn't supported at the moment, so you'll have to:
sudo service transmission-daemon stop
sudo... |
################################################################################
# ForecasterAutoregMultiOutput #
# #
# This work by Joaquin Amat Rodrigo is licensed under a Creative Commons ... |
from django.shortcuts import render
from core.forms.ContatoForm import ContatoForm
from core.components.GerenciadorEmail import Email
def enviarEmailAluno(form):
contexto = {
"aluno":form.cleaned_data['nome'],
"email":form.cleaned_data['email'],
"assunto":form.cleaned_data['assunto'],
... |
# Copyright (c) 2016 PaddlePaddle 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 applic... |
from datetime import date, timedelta
from typing import Optional
from fastapi import APIRouter, Response, status
from src.models import UserPackage
from src.publisher.processing import get_user
from src.publisher.routers.users.db import router as db_router
from src.publisher.routers.users.svg import router as svg_rou... |
import uuid
from django.db import models
from django.utils.translation import gettext_lazy as _
class Member(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False,
help_text=_("ID único seguindo o padrão UUID4.")
)
user =... |
import matplotlib.pyplot as plt
import networkx as nx
def print_graph(vertices, edges, print_dist: bool = False) -> None:
"""
Summary
Args:
vertices (TYPE): Description
edges (TYPE): Description
print_dist (bool, optional): Description
"""
for v in vertices:
print(... |
# -*- coding:utf-8 -*-
__author__ = 'Randolph'
import os
import sys
import time
import logging
sys.path.append('../')
logging.getLogger('tensorflow').disabled = True
import numpy as np
import tensorflow as tf
from tensorboard.plugins import projector
from text_rcnn import TextRCNN
from utils import checkmate as cm
f... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django import VERSION as DJANGO_VERSION
def get_operations():
"""
This will break things if you upgrade Django to 1.8 having already applied this migration in 1.7.
Since this is for a demo site i... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Record... |
from django.apps import AppConfig
class ReviewsConfig(AppConfig):
name = 'pawpals'
|
import xlrd
loc = ("output.xls")
# To open Workbook
wb = xlrd.open_workbook(loc)
wb_sheet = wb.sheet_by_index(0)
with open("pushups.txt", "w") as file:
# For row 0 and column 0
for row_idx in range(1, wb_sheet.nrows):
for col_idx in range(wb_sheet.ncols):
file.write("%s\n... |
"""
Package for analysis of X-ray Absorption Spectroscopy.
"""
|
"""A project to be nitpicked."""
from __future__ import annotations
import itertools
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Iterable, Iterator
import pluggy
from autorepr import autorepr
from loguru import logger
from marshmallow_polyfield import ... |
# 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 ... |
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_mak... |
import numpy as np
class sc_max_pooling:
"""applies max pooling on the absolute values of the sparse codes in Z"""
def __call__(self, Z):
return np.max(np.abs(Z), axis=1)
class max_pooling:
"""applies max pooling on the the sparse codes in Z"""
def __call__(self, Z):
return np.max(Z,... |
import copy
import numpy as np
import uuid
from functools import reduce
from operator import mul
class Suggestion(object):
"""A structure that defines an experiment hyperparam suggestion."""
def __init__(self, params):
self.params = params
def __eq__(self, other):
if self.params.keys() ... |
import random
import math
import time
import copy
from random import randint as rng, shuffle
# GLOBALS
BIRD_X = 300
BIRD_Y = 100
BIRD_WIDTH = 15
BIRD_HEIGHT = 15
GRAVITY = 1.2
JUMP_HEIGHT = 12
BIRD_MAX_VEL = 20
COLUMNWIDTH,OPENING_SIZE = 50,200
VELOCITY_X = 8
# PYGAME
SCREENWIDTH = 600 # pixels... |
"""
mavsim_python
- Chapter 7 assignment for Beard & McLain, PUP, 2012
- Last Update:
2/16/2019 - RWB
"""
import sys
sys.path.append('..')
import numpy as np
import parameters.simulation_parameters as SIM
from chap2.mav_viewer import mav_viewer
from chap3.data_viewer import data_viewer
from chap4.wind_... |
from theano.tensor.nnet.tests import test_neighbours
# We let that import do the init of the back-end if needed.
from .test_basic_ops import mode_with_gpu
from ..neighbours import GpuImages2Neibs
class T_GpuImages2Neibs(test_neighbours.T_Images2Neibs):
mode = mode_with_gpu
op = GpuImages2Neibs
dtypes = ... |
#!/usr/bin/env python
__author__ = "Andre Merzky, Ole Weidner"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
import sys
import saga
def main():
try:
c = saga.Context ('ssh')
c.user_id = 'tg12736'
c.user_cert = '/home/user/ssh/id_rsa_xsede' # private... |
# ===============================================================================
# Copyright 2019 Jan Hendrickx and Gabriel Parrish
#
# 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:/... |
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r"""
name: pipe
author: Daniel Ho... |
# Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
# pylint: disable=line-too-long
solutions = [
{
'url': 'https://chromium.googlesource.com/v8/v8.git@7.9.317.12',
'name': 'v8',
'deps_file': 'DEPS',
'custom_deps': {
'v8/build': None,
'v8... |
from homeassistant.components.water_heater import (
SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE
)
ATTR_DOOR_STATUS = "door_status"
GE_FRIDGE_SUPPORT = (SUPPORT_OPERATION_MODE | SUPPORT_TARGET_TEMPERATURE)
HEATER_TYPE_FRIDGE = "fridge"
HEATER_TYPE_FREEZER = "freezer"
HEATER_TYPE_DISPENSER = "dispenser"
... |
DEFAULT_KERNEL_UPGRADE = "Yes"
DEFAULT_KERNEL_VERSION = ""
DEFAULT_HUGE_PAGES = ""
DEFAULT_CORE_MASK = ""
|
#!/usr/bin/env python3
"""
Quite fast spliting of csv files in python3
Usage:
python3 fastchopcsv.py FILE LINES_PER_FILE
FILE = the file you want to spliting
LINES_PER_FILE = the amount of lines you want to have in the new files
"""
import sys
import os
import time
def file_len(fname):
with open(fname) as f:
... |
# coding=utf-8
# Copyright 2021 The Uncertainty Baselines 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 ap... |
# MIT License
#
# Copyright (c) 2018-2019 Red Hat, Inc.
# 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, m... |
r"""Functional interface"""
from typing import Callable, List, Optional, Tuple
import math
import warnings
import torch
from torch import _VF
from torch._C import _infer_size, _add_docstr
from torch._torch_docs import reproducibility_notes, tf32_notes
# A workaround to support both TorchScript and MyPy:
from typing im... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from patchwork._sample import find_unlabeled, find_fully_labeled
from patchwork._sample import find_partially_labeled
from patchwork._sample import stratified_sample, unlabeled_sample
testdf = pd.DataFrame({
"filepath":["a.jpg", "b.jpg", "c.jpg",... |
"""
Zhihu Crawler
Author: smilexie1113@gmail.com
"""
import requests
import codecs
import json
import time
from collections import deque
from bs4 import BeautifulSoup
from enum import Enum
class DebugLevel(Enum):
verbose = 1
warning = 2
error = 3
end = 4
class ZhihuCrawler(object):
def __in... |
from dnachisel.builtin_specifications import EnforceTranslation
from dnachisel.builtin_specifications.EnforceTranslation import \
EnforceTranslation
from dnachisel.Location import Location
from dnachisel.Specification import SpecEvaluation, Specification
from dnachisel_dtailor_mode.Design import (DesignSpace, Full... |
import csv
from collections import OrderedDict
from dagster import (
AssetMaterialization,
DependencyDefinition,
InputDefinition,
OutputDefinition,
PipelineDefinition,
PythonObjectDagsterType,
SolidDefinition,
dagster_type_loader,
dagster_type_materializer,
repository,
)
from da... |
# Write a Python program to get OS name, platform and release information.
import platform
import os
print(os.name)
print(platform.system())
print(platform.release())
|
# 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... |
# coding: utf-8
# RT.cogs.music - Data Manager ... セーブデータを管理するためのモジュールです。
from typing import List
from .cogs.classes import MusicRawDataForJson
from rtlib import DatabaseManager
from ujson import dumps
class DataManager(DatabaseManager):
DB = "Music"
DJDB = "MusicDJ"
def __init__(self, ... |
#!/usr/bin/env pytest
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test RFC 15 "mask band" default functionality (nodata/alpha/etc)
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
################################################... |
"""This module contains the general information for BiosVfAllUSBDevices ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class BiosVfAllUSBDevicesConsts:
SUPPORTED_BY_DEFAULT_NO = "no"
SUPPORTED_BY_DEFAULT_YES = "yes"
... |
# coding=utf8
import json
from typing import Dict, List, Set
import unicodedata
print(ord('alibaba'))
ranges = [
# (ord(u"\u3300"), ord(u"\u33ff")), # compatibility ideographs
# (ord(u"\ufe30"), ord(u"\ufe4f")), # compatibility ideographs
# (ord(u"\uf900"), ord(u"\ufaff")), # compatibility ideographs
... |
# -*- coding: utf-8 -*-
"""Cisco DNA Center RunReadOnlyCommandsOnDevices data model.
Copyright (c) 2019-2021 Cisco Systems.
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, in... |
"""All keyboards for external users that don't own the poll."""
from typing import List
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from pollbot.enums import CallbackType
from pollbot.i18n import i18n
from pollbot.models.user im... |
#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
A test for RPC users with restricted permissions
"""
import http.client
import os
import urllib.parse
... |
# 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 ... |
import json
import sqlite3 as sql
class DB:
def __init__(self):
self.db_name = 'roster.sqlite'
self.con = ''
self.cur = ''
self.jfile = ''
self.fname = input('Enter file name: ')
if len(self.fname) < 1:
self.fname = 'roster_data.json'
self.jfile... |
# coding: utf-8
from typing import Dict, List # noqa: F401
from fastapi import ( # noqa: F401
APIRouter,
Body,
Cookie,
Depends,
Form,
Header,
Path,
Query,
Request,
Response,
Security,
status,
)
from acapy_wrapper.models.extra_models import TokenModel # noqa: F401
fr... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("RootTester")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
process.load('Configuration.Geometry.GeometryExtended2026D80_cff')
process.load('Geometry.FbcmGeometryBuilde... |
import attr
from marshmallow_annotations.ext.attrs import AttrsSchema
@attr.s(auto_attribs=True, kw_only=True)
class Tag:
tag_name: str
def __init__(self, tag_name: str):
self.tag_name = tag_name
class TagSchema(AttrsSchema):
class Meta:
target = Tag
register_as_scheme = True
|
import argparse
import glob
import json
import logging
import os
import random
import helper
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from transforme... |
from base import DatadogBaseAction
from datadog import api
class DatadogScheduleMonitorDowntime(DatadogBaseAction):
def _run(self, **kwargs):
return api.Downtime.create(**kwargs)
|
#!/usr/bin/python3
import os
import argparse
from robotpkg_helpers import RobotpkgSrcIntrospection
class RpkghAnalyzeOrganization:
def __init__(self):
self.handle_options()
self.analyze_organization()
def analyze_organization(self):
# Reading rpkg_mng_root
# On line co... |
#-------------------
# demo of mean-shift and camshift
# http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_video/py_meanshift/py_meanshift.html
#-------------------
import numpy as np
import cv2
vcap = cv2.VideoCapture(0)
nw0 = vcap.get(cv2.CAP_PROP_FRAME_WIDTH)
nh0 = vcap.get(cv2.CAP_PROP_... |
# -*- coding: utf-8 -*-
import os
import datetime
from distutils import dir_util
import pytest
from ...buffered_generator import BufferedGenerator
from ...reader import DetectionReader, GroundTruthReader
from ...types.detection import Detection
from ...types.groundtruth import GroundTruthPath, GroundTruthState
@pyte... |
# Copyright 2018 United States Government as represented by the Administrator of
# the National Aeronautics and Space Administration. No copyright is claimed in
# the United States under Title 17, U.S. Code. All Other Rights Reserved.
# The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
# un... |
Is_training=True
class Training_arg:
G_num = 4
level_num = 3
conv_shape = (3, 3)
task = 'scannet'
class_num = 21
learning_rate = 5e-4
epoch_num = 50
decay_epoch = 5
train_size = 119382
test_size = 10327
save_epoch = 3
test_epoch = 2
feature_channel = 8
is_point_... |
"""
State Space Representation, Kalman Filter, Smoother, and Simulation Smoother
Author: Chad Fulton
License: Simplified-BSD
"""
import numpy as np
from .kalman_smoother import KalmanSmoother
from . import tools
SIMULATION_STATE = 0x01
SIMULATION_DISTURBANCE = 0x04
SIMULATION_ALL = (
SIMULATION_STATE | SIMULATIO... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: image_procedure.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _... |
"""
An exercise that summarizes what you have learned in this Session.
Authors: David Mutchler, Dave Fisher, Vibha Alangar, Amanda Stouder,
their colleagues and Emily Wilcox.
"""
########################################################################
# Done: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE... |
# qubit number=2
# total number=7
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as... |
"""
sentry.rules.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
Rules apply either before an event gets stored, or immediately after.
Basic actions:
- I want to get notified when [X]
- I want to group events when [X]
- ... |
import threading
from sqlalchemy import Column, String
from . import BASE, SESSION
class LynxChats(BASE):
__tablename__ = "lynx_chats"
chat_id = Column(String(14), primary_key=True)
def __init__(self, chat_id):
self.chat_id = chat_id
LynxChats.__table__.create(checkfirst=True)
INSERTION_LOCK =... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
parsing arguments for sub-commands
"""
__author__ = 'Ming Wang <wangm08@hotmail.com>'
__copyright__ = '2018 by Ming Wang <wangm08@hotmail.com>'
__license__ = 'MIT'
__email__ = 'wangm08@hotmail.com'
__version__ = '0.0.1'
import argparse
def add_trim_args(parser):
... |
# Generated by Django 2.1.15 on 2021-03-08 18:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_account_realm_id'),
]
operations = [
migrations.AddField(
model_name='account',
name='error_date',
... |
# @ali.akgun
# @date: 25.11.2021
# @to do:
# Inputları almak için daha uygun bir yapı oluştur !!!
# Simplify communiciation between other classes !!!
# @bugs:
# @parameters:
# @brief:
# Main Class
try:
# When running from pip installation
from .PhiExt import *
from .Voltage import *
f... |
import sys
import os
sys.path.append(os.path.abspath("../"))
from unittest import TestCase
from komand_microsoft_atp.connection.connection import Connection
from komand_microsoft_atp.actions.get_machine_action import GetMachineAction
import json
import logging
class TestGetMachineAction(TestCase):
def test_inte... |
"""
Settings for {{cookiecutter.project_name}}
Django settings documentation
https://docs.djangoproject.com/en/dev/topics/settings/
Django settings reference
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import environ
env = environ.Env()
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)
A... |
#!/usr/bin/env python
############################################################
from vtk import *
############################################################
# Create sources
line1 = vtkLineSource()
line1.SetPoint1( 1, 0, 0 )
line1.SetPoint2( -1, 0, 0 )
line1.SetResolution( 32 )
points = vtkPoints()
points.Insert... |
#!/usr/bin/env python3
import setuptools
setuptools.setup(
entry_points={
"console_scripts": [
"boxgen = boxgen:main",
],
"distutils.commands": [
"release = distutils_twine:release",
],
},
)
|
import re
from flask_wtf import FlaskForm
from wtforms import TextField, SelectField, BooleanField, IntegerField, TextAreaField
from wtforms.validators import DataRequired, Required, Email, Length, Regexp
from flask_babel import lazy_gettext as __
from app.models import Host, Package
def get_all_hosts():
hosts =... |
# Joint copyright:
# - Copyright 2012,2013 Wikimedia Foundation
# - Copyright 2012,2013 Antoine "hashar" Musso
# - Copyright 2013 Arnaud Fabre
#
# 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 ... |
# file: runme.py
# This file illustrates the shadow-class C++ interface generated
# by SWIG.
import example
# ----- Object creation -----
print "Creating some objects:"
c = example.Circle(10)
print " Created circle", c
s = example.Square(10)
print " Created square", s
# ----- Access a static member -----
pr... |
#!/usr/bin/python
import time
import math
from Adafruit_I2C import Adafruit_I2C
# ============================================================================
# Adafruit PCA9685 16-Channel PWM Servo Driver
# ============================================================================
class PWM :
# Registers/etc.
... |
from lxml import etree
from lxml.html.clean import Cleaner
from .exceptions import MetaPubError, BaseXMLError
def parse_elink_response(xmlstr):
""" return all Ids from an elink XML response
:param xmlstr:
:return: list of IDs, or None if XML response empty
"""
dom = etree.fromstring(xmlstr)
... |
# Copyright 2017 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from . models import Book
# Create your views here.
def index (request):
list_book = Book.objects.all()
html = ''
for books in list_book:
publisher = str(books.publisher)
html += '<a>' + str(books.title) +... |
import pronto
import zipfile
import gzip
import json
import networkx as nx
import time
import re
import MedGenParser
import HpoParser
import HGNCParser
# since this the Phenotype API is in a different folder we need to add it to the python path
import sys
sys.path.insert(0, '../PhenotypeAPI/')
import PhenotypeCorrel... |
from typing import List
import numpy as np
class Normalize(object):
"""Normalize a image with mean and standard deviation.
This transform only test opencv Image.
Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
channels, this transform will normalize each channel of the i... |
import _plotly_utils.basevalidators
class StreamValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="stream", parent_name="treemap", **kwargs):
super(StreamValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from pathlib import Path
import time
from typing import List
import pytest
from pytest_mock import MockerFixture
from pyrepo.git import Git
from pyrepo.inspecting import InvalidProjectError
@pytest.mark.parametrize(
"gitoutput,result",
[
("2019\n2019\n2018\n2016", [2016, 2018, 2019]),
("2018\n... |
import shutil
from os import system
import pytest
@pytest.fixture(params=["t1-linear", "t1-volume"])
def cli_commands(request):
if request.param == "t1-linear":
test_input = [
"t1-linear",
"data/dataset/OasisCaps_example",
"results/quality_check.tsv",
"--no... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import enum
import os
class FileUse(enum.Enum):
INPUT = 1,
GENERATED = 2,
OUTPUT = 3
class FileRef:
def __init__(self, tag, ext, use, output_step=None):
self.tag = tag
self.output_step = None
self.ext = ext
self.use = use
def __eq__(self, b):
return self.t... |
"""Unit tests for tftpy."""
# vim: ts=4 sw=4 et ai:
# -*- coding: utf8 -*-
import unittest
import logging
import tftpy
import os
import time
import threading
from contextlib import contextmanager
from errno import EINTR
from multiprocessing import Queue
from shutil import rmtree
from tempfile import mkdtemp
log = log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.