content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) 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 co... |
def test_requirements(supported_configuration):
pass
|
import os
import sys
import math
import scipy.signal
import schemasim.schemas.l0_schema_templates as st
class PhysicalCondition(st.RoleDefiningSchema):
def __init__(self):
super().__init__()
self._type = "PhysicalCondition"
self._meta_type.append("PhysicalCondition")
self._roles ... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2020 Intel Corporation
""" ETCD Data Write Tool """
import argparse
import logging
import os
import sys
import eis_integ
def parse_arguments(_cli_args):
""" Parse argument passed to function """
parser = argparse.ArgumentParser(descr... |
from app.validation.validation import validate, ARGS, KWARGS
import json
import os
__db_items__ = "db/items"
class Item:
def __init__(self):
pass
@validate(4, ARGS)
def save(self, id, name, price, qty):
with open(f"{__db_items__}/{name}.json", 'w') as f:
data = {
... |
import json
from setuptools import setup, find_packages
from pydoccano import __version__
def requirements():
requirements_list = []
with open('Pipfile.lock', "r") as requirements:
data = json.load(requirements)
data = data['default']
for i in data:
try:
req = i + data[i... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import time
from multiprocessing import Process
import pytest
import six
import thriftpy2
from thriftpy2.http import make_server as make_http_server, \
make_client as make_http_client
from thriftpy2.protocol import TApacheJSONProtocolFact... |
#!/usr/bin/env python
""" """
# Script information for the file.
__author__ = "Philippe T. Pinard"
__email__ = "philippe.pinard@gmail.com"
__version__ = "0.1"
__copyright__ = "Copyright (c) 2015 Philippe T. Pinard"
__license__ = "GPL v3"
# Standard library modules.
import unittest
import logging
import os
import temp... |
import argparse
from multiprocessing import Pool
from grit.occlusion_detection.occlusion_detection_geometry import OcclusionDetector2D
from grit.core.base import create_folders
from igp2.data import ScenarioConfig
def prepare_episode_occlusion_dataset(params):
scenario_name, episode_idx, debug, debug_steps = par... |
# This is the base module that will be imported by Django.
# Try to import the custom settings.py file, which will in turn import one of the deployment targets.
# If it doesn't exist we assume this is a vanilla development environment and import .deployments.settings_dev.
try:
from .settings import * # noqa
excep... |
http://stackoverflow.com/questions/2339101/knights-shortest-path-chess-question
|
import numpy as np
import pandas as pd
import pickle
import os
import json
import glob
import scipy
from ngboost import NGBRegressor
from ngboost.distns import Normal
from ngboost.learners import default_tree_learner
from ngboost.scores import MLE, LogScore
from sklearn.model_selection import KFold
from sklearn.metrics... |
"""Runs the webserver."""
from absl import app
from absl import flags
from absl import logging
from icubam import config
from icubam.db import store
flags.DEFINE_string('config', 'resources/config.toml', 'Config file.')
flags.DEFINE_string('dotenv_path', None, 'Optionally specifies the .env path.')
flags.DEFINE_enum(... |
from time import sleep
def msg(string):
print('~' * (len(string) + 2))
print(f' {string} ')
print('~' * (len(string) + 2))
while True:
print('\33[30;42m', end='')
msg('Sistema de ajuda PyHELP')
user = str(input('\033[mFunção ou Biblioteca \033[32m>>>\033[m '))
if user.lower() == 'fim':
... |
import unittest
from streamlink.plugins.schoolism import Schoolism
class TestPluginSchoolism(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'https://www.schoolism.com/watchLesson.php',
]
for url in should_match:
self.assertTrue(Schoolism.can_ha... |
""""Process the results of DrFact and DrKIT"""
import json
import sys
from tqdm import tqdm
prediction_file = sys.argv[1]
output_file = sys.argv[2]
outputs = []
with open(prediction_file) as f:
print("Reading", f.name)
lines = f.read().splitlines()
for line in tqdm(lines[1:], desc="Processing %s"%f.name):
... |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
def main():
print('234'.isdecimal())
if __name__ == '__main__':
main()
|
def main():
x, y = c(input()), c(input())
if x * y == 0:
return 0
return "S" + ("(S" * ((x * y) - 1)) + "(0" + (")" * (x * y))
def c(x):
return x.count('S')
if __name__ == '__main__':
print(main())
|
# @copyright@
# Copyright (c) 2006 - 2018 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# ... |
#!/usr/bin/python3
"""
Master program """
import multiprocessing
import math
import queue
import time
import pickle
import numpy as np
import pygame
import zmq
class CommProcess(multiprocessing.Process):
"""Communicates with robot."""
def __init__(self, image_queue, command_queue):
super().__init__(d... |
# Generated by Django 3.0.8 on 2020-07-15 09:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Resources', '0008_resume'),
]
operations = [
migrations.CreateModel(
name='People',
... |
import os
import sys
import yaml
import subprocess
from cryptography.fernet import Fernet
secrets_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'secrets.yaml')
def decrypt_secrets(cfg):
with open(os.path.join(cfg['global']['fernet_tokens_path'],'fernet_tokens.txt'), 'r') as token_file:
... |
#Test metadata model
from src.models import metadata
from src import data
from src import utils
import torch
import os
from pytorch_lightning import Trainer
ROOT = os.path.dirname(os.path.dirname(data.__file__))
def test_metadata():
m = metadata.metadata(sites = 1, classes=10)
sites = torch.zeros(20)
... |
from PyQt5 import QtWebEngineWidgets, QtWidgets
from tootbox.core.framework import LayoutView
from tootbox.views.toot import Toot
class Timeline(LayoutView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initialize_ui()
def initialize_ui(self):
self.but... |
from __future__ import unicode_literals
import csv
import io
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.utils.text import slugify
from yourapp.signals import csv_uploaded
from yourapp.validators import csv_file_validator
def uploa... |
import cv2
import numpy as np
# Let's load a simple image with 3 black squares
image = cv2.imread('Hough.jpg')
cv2.waitKey(0)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
# Finding Contours
# Use a copy of the image e.g.... |
import numpy as np
import tensorrt as trt
import cv2
import os
import pycuda.autoinit
import pycuda.driver as cuda
try:
from . import TRT_exec_tools
except ImportError:
import TRT_exec_tools
class Semantic_Segmentation:
def __init__(self, trt_engine_path):
"""
Parameters:
---... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from quant_benchmark.data.base_data_source.default_data_source import DefaultDataSource
import jqdatasdk
#see https://github.com/JoinQuant/jqdatasdk/blob/master/tests/test_api.py
jqdatasdk.auth(username='13922819479', password='123456')
data_source = DefaultDataSource(... |
def f06(word1 = 'paraparaparadise', word2 = 'paragraph'):
ngram = lambda n: lambda tl: [''.join(tl[i:i + n]) for i in range(len(tl) - n + 1)]
X = set(ngram(2)(list(word1)))
Y = set(ngram(2)(list(word2)))
print(X.union(Y))
print(X.difference(Y))
print(X.intersection(Y))
|
import math
def get_digit(n, i):
return n // 10**i % 10
def int_len(n):
if n == 0:
return 1
return int(math.log10(n))+1
def get_new_recipes(n):
recipes = []
for i in range(int_len(n)):
recipes.append(get_digit(n, i))
return recipes[::-1]
def part1(count):
recipes = [3, 7... |
from ._Activate import *
from ._Deactivate import *
from ._Completed import *
from ._Startup import *
from ._Shutdown import *
from ._Recs import *
|
# %% codecell
import os
import numpy as np
from tqdm import tqdm
from shutil import copyfile
# %% codecell
class_indices_S2_rev = {
'Waterbuck': 1,
'Baboon': 2,
'Warthog': 3,
'Bushbuck': 4,
'Impala': 5,
'Oribi': 6,
'Elephant': 7,
'Genet': 8,
'Nyala': 9,
'Setup': 10,
'Bushpig... |
import csv
import os
import random
from .utils import write_into_file, train_val_test_split
def preprocess(in_csv_paths, out_dir_path, val_split, test_split):
dataset = []
for path in in_csv_paths:
with open(path, "r") as file:
reader = csv.DictReader(file)
for row in reader:
... |
"""Output timeseries in NetCDF format.
"""
import glob,os,sys
import pandas as pd
import datetime as dt
import copy
def defaultExtensions():
return ['.nc']
def NCfile(filename,datas):
datas=copy.deepcopy(datas)
fileout=copy.deepcopy(filename)
for i,df in enumerate(datas):
if len(datas)>1:
... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CassandraCluster(object):
"""Implementation of the 'CassandraCluster' model.
Specifies an Object containing information about a Cassandra cluster.
Attributes:
primary_host (string): Primary host from this Cassandra cluster.
seeds (lis... |
"""
A Work-In-Progress agent using Tensorforce
"""
from . import BaseAgent
from .. import characters
class TensorForceAgent(BaseAgent):
"""The TensorForceAgent. Acts through the algorith, not here."""
def __init__(self, character=characters.Bomber, algorithm='ppo'):
super(TensorForceAgent, s... |
## 2. Frequency Distribution ##
fandango_distribution = reviews['Fandango_Ratingvalue'].value_counts().sort_index()
imdb_distribution = reviews['IMDB_norm'].value_counts().sort_index()
print(fandango_distribution)
print('--'*12)
print(imdb_distribution)
## 4. Histogram In Matplotlib ##
fig, ax = plt.subplots()
plt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 03. 円周率
sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
print([len(c.strip(",.")) for c in sentence.split()])
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
from problem.models import Submit, ProblemStats, LogEvent
@receiver(post_save, sender=Submit)
def update_problem_status(sender, instance, **kwargs):
try:
stats: ProblemStats = ProblemStats.obje... |
km = float(input('Informe a distância em KM: '))
v = float(input('Informe a velocidade média: '))
t = km / v
t_h = t // 1
t_m = (t - t_h) * 60
print(f'O tempo da viagem será de {t_h:.0f} horas e {t_m:.0f} minutos.')
|
# from .runner import main
|
import re
from typing import List, Dict, Type
import pkgutil
import inspect
import importlib
import HABApp
from HABApp.core import Items
from HABApp.core.items.base_item import BaseItem
import zone_api.core.actions as actions
from zone_api import platform_encapsulator as pe
from zone_api import device_factory as df
f... |
from unittest import TestCase
from unittest.mock import patch, call
import os
import pytest
from osbot_utils.utils.Dev import pprint
from osbot_utils.utils.Json import json_load_file
from cdr_plugin_folder_to_folder.processing.Analysis_Elastic import Analysis_Elastic
from cdr_plugin_folder_to_folder.utils.testing.Se... |
from seleniumbase import BaseCase
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from parameterized import parameterized
import pytest
from test_thermal.test_CompanyAdmin.test_RoleManagement.RoleManageBase import RoleManageBase
from utilities import utilities
from utilities.... |
"""
Here we're going to code for the local rotations. We're doing an object oriented approach
Left and right are in reference to the origin
"""
__version__ = 1.0
__author__ = 'Katie Kruzan'
import string # just to get the alphabet easily iterable
import sys # This just helps us in our printing
from typing import Di... |
from controller.csi_general import csi_pb2
SUPPORTED_FS_TYPES = ["ext4", "xfs"]
access_mode = csi_pb2.VolumeCapability.AccessMode
SUPPORTED_ACCESS_MODE = [access_mode.SINGLE_NODE_WRITER]
# VolumeCapabilities fields which specify if it is volume with fs or raw block volume
VOLUME_CAPABILITIES_FIELD_ACCESS_TYPE_MOUNT ... |
import pybamm
import numpy as np
import sys
# set logging level
pybamm.set_logging_level("INFO")
# load (1+1D) SPMe model
options = {
"current collector": "potential pair",
"dimensionality": 1,
"thermal": "lumped",
}
model = pybamm.lithium_ion.SPM(options)
# create geometry
geometry = model.default_geome... |
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE.
#
# Distributed under 3-Clause BSD license. See LICENSE file for more information.
#
"""
Mapping Module
"""
# -- STANDARD MAPPI... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : download.py
@Time : 2020/11/08
@Author : Yaronzz
@Version : 1.0
@Contact : yaronhuang@foxmail.com
@Desc :
'''
import os
import aigpy
import logging
import lyricsgenius
from tidal_dl.settings import Settings
from tidal_dl... |
"""
plots how total workseting set increase over time
"""
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../"))
from utils.common import *
import bisect
SLAB_SIZES = [96, 120, 152, 192, 240, 304, 384, 480, 600, 752, 944, 1184, 1480, 1856, 2320, 2904, 3632, 4544, 5680, 71... |
from setuptools import setup
setup(name='carpet',
version='2021',
# description='',
url='https://cfaed.tu-dresden.de/friedrich-home',
author='Anton Solovev, Benjamin M Friedrich',
license='MIT',
packages=['carpet'],
zip_safe=False) |
'''
Convert a neighbors file to human-readable format,
optionally including preferred string expansion.
'''
from hedgepig_logger import log
from .. import nn_io
if __name__ == '__main__':
def _cli():
import optparse
parser = optparse.OptionParser(usage='Usage: %prog')
parser.add_option('-i... |
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2) |
#!/usr/bin/env python
import cv2
# from opencvutils.video import Camera
cam = cv2.VideoCapture(0)
# cam.init(cameraNumber=0, win=(640, 480))
while True:
try:
ret, img = cam.read()
cv2.imshow('img', img)
if cv2.waitKey(1) == 27:
break # esc to quit
except:
# cam.close()
break
cv2.destroyAllWindows(... |
import requests
import json
from xlwt import *
url = "https://api.github.com/users/andrewbeattycourseware/followers"
response = requests.get(url)
data = response.json()
filename = 'githubusers.json'
print(data)
for car in data:
print(car)
#write the Json to a file.
#import json
if filename:
with open(filename, ... |
from .cell_level_analysis import CellLevelAnalysis
from .pixel_level_analysis import PixellevelAnalysis
from .feature_extraction import InstanceFeatureExtraction
from .background_extraction import ExtractBackground
|
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014, pietro partescano
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this ... |
import xml.etree.ElementTree as ET
import urllib2
from sqlalchemy import and_
from datetime import datetime
from .ConnectDB_ParseExcel import *
from stp0_loadCVs import Load_CV_To_DB
from stp4_loadDataValue.helper import LoadingUtils
class CUAHSI_importer():
'''
This class is used to get data putting to Wa... |
"""Fsubs config."""
|
"""Utility functions to check attributes returned in API responses and read from the AWS S3."""
import datetime
import re
def check_attribute_presence(node, attribute_name):
"""Check the attribute presence in the given dictionary or list.
To be used to check the deserialized JSON data etc.
"""
found_... |
gagaStop = Lorentz(name = 'gagaStop',
spins = [ 3, 3, 1 ],
structure = 'FTriPhotonTop(2*P(-1,1)*P(-1,2)) * (Metric(1,2)*P(-1,1)*P(-1,2) - P(2,1)*P(1,2))')
gagaSbot = Lorentz(name = 'gagaSbot',
spins = [ 3, 3, 1 ],
structure = 'FTriPhotonBot(2*P(-1,1)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Zero-DCE++: Learning to Enhance Low-Light Image via Zero-Reference Deep Curve
Estimation
Zero-DCE++ has a fast inference speed (1000/11 FPS on single GPU/CPU for an
image with a size of 1200*900*3) while keeping the enhancement performance of
Zero-DCE.
References:
... |
"""Number constraint names."""
from jsonvl._utilities.venum import Venum
class NumberConstraintNames(Venum):
"""Constraints applied to number types."""
LT = 'lt'
GT = 'gt'
LTE = 'lte'
GTE = 'gte'
EQ = 'eq'
|
import time
import logging
import numpy as np
import torch
import torch.nn as nn
from data import augment, TensorDataset
from diffaugment import DiffAugment
from utils import get_time
def epoch(mode, dataloader, net, optimizer, criterion, args, aug):
loss_avg, acc_avg, num_exp = 0, 0, 0
net = net.to(args.devic... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the dat... |
a, b = [int(x) for x in input().split()]
if a > b:
a, b = b, a
if a & 1:
a += 1
if b & 1:
b -= 1
print(((b - a) // 2 + 1) * (a + b) // 2)
|
from ..SimpleSymbolDownloader import SymbolDownloader
from ..symbols.Generic import Generic
from time import sleep
from ..compat import text
import requests
class TigerDownloader(SymbolDownloader):
def __init__(self):
SymbolDownloader.__init__(self, "tiger")
def _add_queries(self, prefix=''):
... |
from flask import Blueprint
from app.actor import get_hello
import jsonpickle
hello_resource = Blueprint('hello_resource', __name__)
@hello_resource.route('/rest/hello/', defaults={'name': 'world'})
@hello_resource.route('/rest/hello/<name>')
def get(name):
return jsonpickle.encode(get_hello.run(name), unpicklab... |
"""
Copyright 2020 Alexander Brauckmann.
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... |
# coding=utf-8
# Copyright (c) 2016-2018, F5 Networks, 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 applicabl... |
from __future__ import annotations
import logging
import re
from dataclasses import dataclass
from datetime import date
from wordgame_bot.attempt import Attempt, AttemptParser
from wordgame_bot.exceptions import InvalidFormatError, ParsingError
from wordgame_bot.guess import Guesses, GuessInfo
INCORRECT_GUESS_SCORE ... |
# https://leetcode.com/problems/magic-squares-in-grid/description/
#
# algorithms
# Medium (35.25%)
# Total Accepted: 12,752
# Total Submissions: 36,179
# beats 66.41% of python submissions
class Solution(object):
def splitIntoFibonacci(self, S):
"""
:type S: str
:rtype: List[int]
... |
from django import forms
from formfactory import clean_methods
@clean_methods.register
def check_if_values_match(form_instance, **kwargs):
"""Clean method for when a contact updates password.
"""
first_field = form_instance.cleaned_data["first_field"]
second_field = form_instance.cleaned_data["second... |
# File: worker.py
# Aim: Backend worker of the http server
# Imports
import os
import sys
from . import CONFIG
from .local_tools import Tools
tools = Tools()
CONFIG.logger.debug('Worker imported in HTTP package')
# Import other workers
other_folders = [
os.path.join(
os.path.dirname(__file... |
from .forms import UserProfileForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Profile
def display_login(request):
context = {}
ret... |
import tensorflow as tf
import numpy as np
import os
from scipy.io import loadmat
from epi.util import dbg_check
import matplotlib.pyplot as plt
# import tensorflow_probability as tfp
FANO_EPS = 1e-6
neuron_inds = {"E": 0, "P": 1, "S": 2, "V": 3}
def load_SSSN_variable(v, ind=0):
# npzfile = np.load("data/V1_Zs... |
from schematics.types import ModelType, StringType, PolyModelType, FloatType, DateTimeType
from spaceone.inventory.model.sqldatabase.data import Database
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, DateTimeDyField, EnumDyField, \
ListDyField
from spaceone.inventory.libs.schema.me... |
"""Adam Integer Check"""
def prime_adam_check(number: int) -> bool:
"""
Check if a number is Adam Integer.
A number is Adam if the square of the number and square
of the reverse of the number are reverse of each other.
Example : 11 (11^2 and 11^2 are reverse of each other).
"""
# Get the... |
import re
import urllib2
import urllib
import urlparse
import socket
# sniff for python2.x / python3k compatibility "fixes'
try:
basestring = basestring
except NameError:
# 'basestring' is undefined, must be python3k
basestring = str
try:
next = next
except NameError:
# builtin next function doesn... |
class SPI(object):
def __init__(self, clk, MOSI=None, MISO=None):
self.clk = clk
self.MOSI = MOSI
self.MISO = MISO
|
from core.entity.entity_exceptions import EntityOperationNotPermitted, EntityNotFoundException
from core.test.media_files_test_case import MediaFilesTestCase
class BaseTestClass(MediaFilesTestCase):
"""
provides the base class for all test cases
_check_default_fields and _check_default_change must be re-... |
import numpy as np
import torch
from .mask_gen import BoxMaskGenerator
class CutmixCollateWrapper(object):
def __init__(self, batch_aug_fn=None):
self.batch_aug_fn = batch_aug_fn
self.mask_generator = BoxMaskGenerator(
prop_range = (0.25, 0.5),
n_boxes = 3,
rand... |
"""
# BEGIN BINGO_DEMO
>>> bingo = BingoCage(range(3))
>>> bingo()
2
>>> bingo()
0
>>> callable(bingo)
True
# END BINGO_DEMO
"""
# BEGIN BINGO
import random
class BingoCage:
def __init__(self, items):
self._items = list(items) # <1>
random.shuffle(self._items) # <2>
def __call__(self):
... |
from json import dumps
class Node:
def __init__(self, line = 0, column = 0):
self.line = line
self.column = column
@property
def clsname(self):
return str(self.__class__.__name__)
def to_tuple(self):
return tuple([
("node_class_name", self.clsname)
... |
from ckan.common import config
def get_ytp_recommendation_recaptcha_sitekey():
return config.get('ckanext.ytp_recommendation.recaptcha_sitekey')
|
# The MIT License(MIT)
# Copyright (c) 2013-2014 Matt Thomson
# 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, mo... |
import itertools
a = input()
s = input().split()
n = int(input())
L = list(itertools.combinations(s, n))
f = filter(lambda x: 'a' in x, L)
print("{:.4f}".format(len(list(f))/len(L)))
|
from django.conf.urls import include, url
urlpatterns = [
# browsable REST API
url(r'^api/', include('osmaxx.rest_api.urls')),
url(r'^version/', include('osmaxx.version.urls', namespace='version')),
]
|
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 1 - Driving in Shapes
"""
########################################################################################
# Imports
########################################################################################
import sys
sys.path.insert(1, ".... |
import pyOcean_cpu as ocean
a = ocean.zeros([5,5])
a[1,...,3] = 99
print(a)
|
import sqlite3
import pandas as pd
from .. import CONFIG
import datetime
from ..scrape.utils import PROPER_DATE_FORMAT
class DB_Query():
def __init__(self, column_names, rows):
self.column_names = column_names
self.rows = rows
def to_df(self):
return pd.DataFrame(self.rows, columns=s... |
#!/usr/bin/env python3
"""
This is the player application called by remctl or
through SSH; it is the replacement for the Perl command
'acoustics' and provides the same functionality.
"""
import sys
import os
import importlib
sys.path.append(os.path.dirname(sys.argv[0]) + '/lib')
from amp import db, config
if __na... |
import argparse
import yaml
import os
import anndata as ad
from morphelia.preprocessing import *
from morphelia.features import *
def run(inp):
"""Preprocess morphological annotated data."""
# where to save figures
figdir = os.path.join(inp['output'], './figures/')
# load data
inp_data = os.path.... |
"""Encoder definition for transformer-transducer models."""
import torch
from espnet.nets.pytorch_backend.transducer.blocks import build_blocks
from espnet.nets.pytorch_backend.transducer.vgg2l import VGG2L
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
from espnet.nets.pytorch_backend.tran... |
import gym
import quadruped_gym.gym # noqa: F401
def test_reset():
env = gym.make('A1BulletGymEnv-v0')
observation = env.reset()
assert observation in env.observation_space
def test_step():
env = gym.make('A1BulletGymEnv-v0')
env.reset()
for _ in range(10):
env.step(env.action_spac... |
import numpy as np
if __name__=="__main__":
N=list(map(int,input().split()))
print(np.zeros(N,int))
print(np.ones(N,int)) |
from jivago.jivago_application import JivagoApplication
from jivago.wsgi.annotations import Resource
from jivago.wsgi.methods import GET
@Resource("/")
class HelloResource(object):
@GET
def get_hello(self) -> str:
return "Hello World!"
app = JivagoApplication()
if __name__ == '__main__':
app.r... |
import pandas
from matplotlib import pyplot
df = pandas.DataFrame([431-106,106])
df = df.transpose()
df.columns=['complete','incomplete']
df.plot(kind='bar', stacked=True, legend=False)
pyplot.show()
|
from typing import Tuple, Union, List, Optional
from sectionproperties.pre import sections
import numpy as np
import shapely
def create_line_segment(
point_on_line: Union[Tuple[float, float], np.ndarray],
vector: np.ndarray,
bounds: tuple,
):
"""
Return a LineString of a line that contains 'point... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.