content stringlengths 5 1.05M |
|---|
# Devoir 4
# Sofiane Bouabdallah et Félix Chiasson
import turtle
def draw_square(position, size):
'''
(int, int) -> None
Draw a square
'''
position.pendown()
position.fill(False)
for _ in range(4):
position.forward(size)
position.right(90)
position.pe... |
import warnings
from django.conf import settings
if hasattr(settings, 'HASHID_FIELD_ALLOW_INT'):
warnings.warn("HASHID_FIELD_ALLOW_INT is deprecated, use HASHID_FIELD_ALLOW_INT_LOOKUP",
DeprecationWarning, stacklevel=0)
if not hasattr(settings, 'HASHID_FIELD_ALLOW_INT_LOOKUP'):
setat... |
import os
os.mkdir("data")
os.mkdir("data/test")
os.mkdir("data/test/cats")
os.mkdir("data/test/dogs")
os.mkdir("data/train")
os.mkdir("data/train/cats")
os.mkdir("data/train/dogs")
os.mkdir("data/validation")
os.mkdir("data/validation/cats")
os.mkdir("data/validation/dogs")
|
import re
from embeds import EMBEDLY_KEY, EMBED_REGEX, USER_AGENT
from embedly import Embedly
def detect_embedded_content(text):
results = []
client = Embedly(key=EMBEDLY_KEY, user_agent=USER_AGENT)
for url in re.findall(EMBED_REGEX, text):
results.append(client.oembed(url))
return results
|
""" Grid Search for Hyperparameters """
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.model_selection import (
GridSearchCV,
train_test_split,
)
# in short, cla... |
words = input().split(', ')
result = [f'{w} -> {len(w)}' for w in words]
print(', '.join(result))
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : LeetCode1337.py
@Time : 2020/08/25 19:49:07
@Author : kangqing
@Contact : kangqing.37@gmail.com
@Software: VS Code
@Desc : LeetCode1337 方阵中战斗力最弱的 K 行
'''
# here put the import lib
from typing import List
class Solution:
def kWeakestR... |
import os
from crawler.requester.parser.wab_page_parser import WebPageParser
class TestWebPageParser:
def test_parse(self):
with open(f'{os.path.dirname(__file__)}/fixture/test_wab_page_parser/test_parse.html') as f:
test_html = f.read()
parser = WebPageParser()
result = pars... |
from notion.block import BLOCK_TYPES, TextBlock
from .maps import patched_property_map
class PatchedTextBlock(TextBlock):
raw_data = patched_property_map("title")
BLOCK_TYPES['text'] = PatchedTextBlock
|
"""dhamma_backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
def menorpos(numeros):
cont = menor = pos = 0
for c, i in enumerate(numeros):
cont = cont + 1
if cont == 1:
menor = i
pos = c
else:
if i < menor:
menor = i
pos = c
return pos
v = [3, 5, 1, 30, 50, 100]
print(menorp... |
# 44
import math
import itertools
class Solve(object):
def __init__(self):
pass
def solve(self):
"""
Solve: find pentagon number small, big (small < big), s.t.:
delta = big - small (assume delta < small),
sum = small + big are also pentagon numbers
We loop big_... |
from http.server import HTTPServer, BaseHTTPRequestHandler
from optparse import OptionParser
ECHO_PORT = 27080
class RequestHandler(BaseHTTPRequestHandler):
def do_FRIDA(self):
request_path = self.path
request_headers = self.headers
content_length = request_headers.get('content-length')
... |
import sys
import os
from cx_Freeze import setup, Executable
version = "1.2.1.1"
# Dependencies are automatically detected, but it might need fine tuning.
def files_from_folder(folder):
return [(folder, x) for x in os.listdir(folder)]
#include_files = files_from_folder("resources/")
#include_files.extend(files_f... |
'''
Here we will learn some skills of encode and decode.
'''
from urllib.request import urlopen
from io import StringIO
from io import open
import csv
'''
textPage = urlopen("http://www.pythonscraping.com/pages/warandpeace/chapter1-ru.txt")
print(str(textPage.read(), 'utf-8'))
'''
'''
data = urlopen("http://www.py... |
from ramen.core.signal import Signal
from ramen.core.node import parentable
from ramen.core.node import parameter
class Node(parentable.Parentable):
def __init__(self, parent=None, label=None, node_id=0, graph=None):
super(Node, self).__init__()
# If a parent is provided, use the parent's graph.
... |
import os
from interface_test_platform import settings
from interface_test.models import InterfaceMock, SceneMock
from interface_test.common.file_operate import to_json_file
mock_data_path = os.path.join(settings.BASE_DIR, 'mock_data')
if not os.path.exists(mock_data_path):
os.makedirs(mock_data_path)
mock_settin... |
import numpy as np
import jieba
import jieba.posseg as pseg
class TextRank(object):
def __init__(self, sentence, window, alpha, iternum):
self.sentence = sentence
self.window = window
self.alpha = alpha
self.edge_dict = {} #记录节点的边连接字典
self.iternum = iternum#迭代次数
... |
################################################################################
# Copyright (C) 2016-2020 Abstract Horizon
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License v2.0
# which accompanies this distribution, and is available at
# http... |
import numpy as np
import inspect
import os
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
import shutil
import time
import abc
from itertools import zip_longest
import dill
import itertools
... |
from typing import Any
import serial
import time
class Serial:
"""
Handle serial communication between the python script
and the microcontroller
"""
# CONSTRUCTOR
def __init__(
self,
PORT: str = 'COM3',
BAUD_RATE: int = 9600,
... |
traffic_ip_groups = {
'children': [
{
'href': '/api/tm/5.2/config/active/traffic_ip_groups/Default%20EIP',
'name': 'Default EIP'
},
{
'href': '/api/tm/5.2/config/active/traffic_ip_groups/TLS%201.0%20Disabled',
'name': 'TLS 1.0 Disabled'
... |
# geoip/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
# requires an installation of the C library at https://github.com/maxmind/geoip-api-c
from django.contrib.gis.geoip import GeoIP
import wevote_functions.admin
from wevote_functions.functions import get_ip_from_headers, positive_value_... |
# Generated by Django 4.0.2 on 2022-03-06 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('complaints', '0009_alter_complaints_status'),
]
operations = [
migrations.AlterField(
model_name='complaints',
name=... |
from unittest import mock
import pytest
from directory_constants import user_roles
from django.core import signing
from django.urls import reverse
from rest_framework.test import APIClient
from company.models import Company, CompanyUser
from company.tests.factories import CompanyFactory
from enrolment.tests.factories... |
import contextlib
import functools
import os
import re
import time
from collections import namedtuple
from leapp import reporting
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.stdlib import CalledProcessError, api
from leapp.models import RHSMInfo
_RE_REPO_UID = re.compile(r'Repo ID:\s*([^... |
import numpy as np
from matplotlib import pyplot as plt
import random
# ----------------- CONSTANTS SETTINGS -----------------------
BETA = 1000000000
# ----------------- CLOUDING SYSTEM ENVIRONMENT --------------
class cloud_Env:
def __init__(self, U, M, D, W, Tmax, P, R_sbs, f_local, f_sbs, f_mbs, sigma_l, sig... |
import factory
from factory import Faker
__all__ = [
'SubscriptionFactory',
'ResourceGroupFactory',
]
class SubscriptionFactory(factory.django.DjangoModelFactory):
uuid = Faker('uuid4')
class Meta:
model = 'msazure.Subscription'
django_get_or_create = ('uuid',)
class ResourceGroupF... |
#!/usr/bin/python3
from datetime import datetime
from lxml import etree
import re
import urllib.request
class TwitterScraper():
def __init__( self, url ):
self.entries = []
tree = None
with urllib.request.urlopen( url ) as f:
tree = etree.HTML( f.read() )
tweets = tree... |
str = input().lower()
al = 'qwertyuiopasdfghjklzxcvbnm'
ch = []
for i in al:
ch.append(str.count(i))
l = [(i, v) for i, v in enumerate(ch) if v == max(ch)]
if (len(l) > 1):
print('?')
else:
print(al[l[0][0]].upper()) |
import os
from datetime import timedelta
from pathlib import Path
from django.utils.translation import gettext_lazy as _
from dotenv import load_dotenv
load_dotenv()
ENV = os.environ
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = ENV['SECRET_KEY']
DEBUG = int(ENV.get('DJANGO_DEVELOPMENT', False))
... |
from .gfootball_no_pack_bits import GFootball as GFootballNoPackBits
from .base_vtrace_network import AgentOutput
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from absl import logging
import tensorflow as tf
import gym
#logging.set_verbosity(logging.DEBUG)
class MarlGridRayGFootballNoPackBits(TFModelV2):
... |
#!/usr/bin/env python
#
# description: Generate Parentheses
# difficulty: Medium
# leetcode_num: 22
# leetcode_url: https://leetcode.com/problems/generate-parentheses/
#
# Given n pairs of parentheses, write a function to generate all combinations
# of well-formed parentheses.
#
# For example, given n = 3, a solution s... |
from ecgdetectors import Detectors
import data_read
from pyhrv.hrv import hrv
from pyhrv.time_domain import hr_parameters
from pyhrv.frequency_domain import frequency_domain
from pyhrv.tools import nn_intervals, plot_ecg, heart_rate, tachogram
def heart_rate_variability(sample, lead, rpeak_method = 'string'):
cu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#######################################################################
## PRIMITIVA y EUROMILLONES ##
## Programa Principal para enviar por Telegram las combinaciones ##
## y resultados. ... |
class Mobility:
def __init__(self):
self.matrix = None
|
import asyncio
from typing import List, Literal, Union
from datetime import datetime
from .http import HTTPClient
from .routes import *
from .errors import *
from .routes.base import *
from .types import *
from .utils import *
from .iterators import *
class Client:
"""MangaDex Client
Parameters
-----... |
import numpy as np
from ...Specification.SpecEvaluation import SpecEvaluation
from ...biotools import dict_to_pretty_string
from .BaseCodonOptimizationClass import BaseCodonOptimizationClass
class MatchTargetCodonUsage(BaseCodonOptimizationClass):
"""Codon-optimize a sequence so it has the same codon usage as a ... |
from typing import Any
from cloud.amazon.common.base_service_generated_instance import BaseSGI
from properties_and_methods import CachedProperty
from types_extensions import void, const, list_type, dict_type
class AmazonS3Bucket(BaseSGI):
def __init__(self, bucket_name: str, parent, exception_level: int) -> voi... |
import json
import os
import sys
import re
import shutil
import subprocess
import tempfile
import time
import datetime
import urllib.error
import urllib.request
from pathlib import Path
from typing import List, Tuple, Dict
CONNECTION_RETRY_SECONDS = 60
class Logger:
debug = False
@staticmethod
def log(... |
from .types import Module, ResultInfo, ConsoleErrorInfo, ConsoleErrorField
"""
This file contains all currently known 2DS/3DS result and error codes (hexadecimal).
There may be inaccuracies here; we'll do our best to correct them
when we find out more about them.
A result code is a 32-bit integer returned when callin... |
# -*- coding: utf-8 -*-
"""login form with Email rather than Username"""
from django import forms
from django.contrib.auth import authenticate, REDIRECT_FIELD_NAME
from django.contrib.auth.forms import PasswordChangeForm, PasswordResetForm, SetPasswordForm
from django.utils.translation import ugettext as _, ugettext_l... |
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.translation import gettext_lazy as _
def validate_email_list(email_list):
if not email_list:
# Empty list or None is fine
return email_list
# First check if it an actual list... |
from collections import defaultdict
from lxml import etree
import os
from django.conf import settings
from django.core.management import BaseCommand
from corehq.apps.app_manager.util import all_apps_by_domain
from custom.openclinica.utils import simplify, Item, odm_nsmap
import yaml
class Command(BaseCommand):
d... |
# (C) Datadog, Inc. 2019
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import pytest
from datadog_checks.dev.ssh_tunnel import socks_proxy
from datadog_checks.dev.terraform import terraform_run
from datadog_checks.dev.utils import get_here
@pytest.fixture(scope='session... |
import core.base as base
import spark.spark_verifier as spark_verifier
class SparkSmokeTest(base.SmokeTest):
def __init__(self, cmd_line_type='AMBARI'):
super().__init__('SPARK', 'SPARK_JOBHISTORYSERVER', logname='smoketest-spark.log', stop_type=cmd_line_type,
process_user='spark... |
import requests
import pandas as pd
import numpy as np
import datetime
def conv_to_list(obj):
"""
將物件轉換為list
"""
if not isinstance(obj, list):
results = [obj]
else:
results = obj
return results
def df_conv_col_type(df, cols, to, ignore=False):
"""
一次轉換多個欄位的dtype
"... |
import json
import time
import typing
def attempt_file_write(
path: str,
contents: typing.Union[str, bytes],
mode: str = 'w',
offset: int = 0
) -> typing.Union[None, Exception]:
"""
Attempts to write the specified contents to a file and returns None if
successful, or the ra... |
word_list = input().split("-")
ans = ""
for word in word_list:
ans += word[0]
print(ans)
#Did this one in Java first before I bothered learning Python
#Take a look at how much shorter this version of it is |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-08-14 17:01:39
LastEditors: xiaoshuyui
LastEditTime: 2020-10-14 10:52:50
'''
class Ori_Pro(object):
def __init__(self, oriImg, processedImg):
self.oriImg = oriImg
self.processedImg = processedImg
def do_nothing():
... |
# Copyright 2019 Objectif Libre
#
# 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/local/bin/python
"""
vector to matrix
"""
from __future__ import print_function
from __future__ import division
import sys
import argparse
import subprocess
import shlex
import logging
import itertools
import time
import gzip
import re
import os
import math
import uuid
import socket
from datetime import datet... |
import os
import numpy as np
import pandas as pd
from pyntcloud import PyntCloud
BASE_DIR = r"G:\Capstone\pointnet"
ply_folder = os.listdir(os.path.join(BASE_DIR, "data", "ply_files"))
# Iterate through ply files in folder
for idx, ply_file in enumerate(ply_folder):
ply_data = PyntCloud.from_file(os.pat... |
# Generated by Django 3.0.6 on 2020-09-14 20:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('modelokits', '0012_kitsprincipal'),
]
operations = [
migrations.AddField(
model_name='kitsproducts',
n... |
import os
import sys
import argparse
from typing import Union
from aws_cli_utils.common_utils.aws import glue_client
from albertquiroga_utils.network import build_ssh_command
from albertquiroga_utils.aws import extract_ip_address_from_aws_hostname
from botocore.exceptions import ClientError
GLUE_ENDPOINT_USERNAME = ... |
"""Module to select which simulation to run."""
import model_and_simulate.utilities.pygame_simple as pygame_simple
from base_start_menu import pygame_simulations, matplotlib_simulations, BaseStartScreen
def run_pygame_main() -> bool:
"""Runs the simulation within pygame logic."""
reset = True
while reset... |
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel, StreamFieldPanel
from wagtail.api import APIField
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from wagtail.images.api.fields import ImageRenditionField
from wagtail.images... |
from .base import show_nplusones
|
from unittest.mock import AsyncMock, MagicMock, patch, PropertyMock
import pytest
from aio.run.checker import (
Checker, CheckerSummary)
from aio.run.runner import Runner
class DummyChecker(Checker):
def __init__(self):
self.args = PropertyMock()
class DummyCheckerWithChecks(Checker):
checks... |
from mnb import *
def build_plan(p: Plan):
p.require_api(1,0)
p.build_image("bberkgaut/mnb:%s" % MNB_VERSION, context_path="mnb-main")
# plantuml_dir = Path("containers/plantuml")
# plantuml_version = (plantuml_dir / "VERSION").read_text().strip()
# plantuml_image = p.build_image("bberkgaut/mnb-pl... |
from tkinter import filedialog as fd
import subprocess
import os
from .logger import logger
class ConfigCls(object):
def __init__(self, *args, **kwargs):
self.default_mesh_size = 10
self._docker_path = None
self.clean_up = True # clean all docker volumes after run
@property
d... |
# -*- coding: utf-8 -*-
# @Author: JustinXu
# @Date: 2018-05-09 20:11:41
# @Last Modified by: tiany
# @Last Modified time: 2018-05-09 21:03:21
######################### import stuff ##########################
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functi... |
'''
字符大小写排序
中文English
给定一个只包含字母的字符串,按照先小写字母后大写字母的顺序进行排序。
一招partiton 走天下
'''
|
from __future__ import print_function
import json
import requests
import hmac
import urllib
import hashlib
import base64
class Rule(object):
def __init__(self, user_key, private_key):
self.user_key = user_key
self.private_key = private_key
self.protocol = "https"
self.endpoint = "... |
#!/usr/bin/env python
import sys
import doctest
def main():
if len(sys.argv) != 2:
print('modo de usar: {0} arquivo.rst'.format(sys.argv[0]))
return 2
else:
nome_doc = sys.argv[1]
qt_falhas, qt_testes = doctest.testfile(nome_doc,
module_relative=... |
import os
import torch
import torch.nn.functional as F
import torch.multiprocessing as mp
import torch.distributed.rpc as rpc
from torch.distributed.rpc import RRef
from torch.distributed.rpc import rpc_sync
import torch.distributed.autograd as dist_autograd
from torch.distributed.optim import DistributedOptimizer
fr... |
# vim:set et sts=4 sw=4:
#
# ibus - The Input Bus
#
# Copyright (c) 2007-2010 Peng Huang <shawn.p.huang@gmail.com>
# Copyright (c) 2007-2010 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Sof... |
"""Training algorithms."""
import logging
import itertools
from collections import OrderedDict
from picklable_itertools.extras import equizip
import numpy as np
import theano
from theano import tensor
from blocks.roles import add_role, ALGORITHM_HYPERPARAMETER
from blocks.theano_expressions import l2_norm
from blocks.... |
import os
from simtk import unit
import cg_openmm
from simtk.openmm.app.pdbfile import PDBFile
from cg_openmm.cg_model.cgmodel import CGModel
from cg_openmm.simulation.tools import run_simulation
import numpy as np
###
#
# This example demonstrates how to run an NVT
# simulation for a coarse grained model in OpenMM,
#... |
# Generated by Django 3.2.2 on 2021-07-04 21:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blweb', '0008_alter_vehi... |
import torch
from pytorchfi.core import fault_injection as pfi_core
from .util_test import CIFAR10_set_up_custom
class TestWeightFi:
"""Testing focuses on weight perturbations."""
def setup_class(self):
torch.manual_seed(0)
batch_size = 1
workers = 1
channels = 3
img... |
ang1 = int ( input (" primeiro angulo ? " ))
ang2 = int ( input (" Segundo angulo ? " ))
ang3 = int ( input (" Terceiro angulo ? " ))
if (ang1 + ang2 +ang3 == 180):
print ('Pode formar triângulo')
if (ang1 == 90) or (ang2 == 90) or ( ang3 == 90):
print ('Triângulo Retângulo')
elif (ang1 < 90) and... |
# --------------
import numpy as np
import pandas as pd
# Read the data. Data is already loaded in the variable `path` use the `delimeter = ';'`.
data = pd.read_csv(path, delimiter=';')
print(data.shape)
# Replace the `unknown` values with the `Nan` and check the value count of missing values and drop the missing rows... |
#A task is a some work to be done which can be assumed takes 1 unit of time.
# Between the same type of tasks you must take at least n units of time before running the same tasks again.
#Given a list of tasks (each task will be represented by a string),
# and a positive integer n representing the time it takes to ru... |
import pytest
import nengo
from nengo.base import NengoObjectParam
from nengo.exceptions import ValidationError
def test_nengoobjectparam():
"""NengoObjectParam must be a Nengo object and is readonly by default."""
class Test:
nop = NengoObjectParam("nop")
inst = Test()
# Must be a Nengo o... |
import re
from ewatercycle_experiment_launcher.api import hello
from ewatercycle_experiment_launcher.hub import JupyterHubClient
from ewatercycle_experiment_launcher.process import process_notebook
class TestProcessNotebook:
def test_withoutWorkspace(self, mocked_client: JupyterHubClient):
request = {
... |
"""Calculate beta diversity and ordination."""
import logging
import pickle
from os import path
import pandas as pd
from skbio.diversity import beta_diversity
from skbio.stats.ordination import pcoa
from skbio.stats import subsample_counts
logging.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s")
log = l... |
"""Provides the RIS Peers endpoint."""
import ipaddress
from collections import namedtuple
from datetime import datetime
from typing import Optional
from prsw.validators import Validators
class RISPeers:
"""
This data call provides information on the peers of RIS - ASN, IP address and
number of shared ... |
"""
此模块做停车管理系统的服务端
Author:Recall
Date: 2018-10-15
module: socket、Thread、sys、os、time
Email:
"""
from socket import *
from threading import Thread
from setting import *
from car_mysql import *
from mysql_function import *
import sys,os,time,random
class car_server(object):
def __init__(self):
self.sockfd ... |
"""Generated message classes for resourcesettings version v1.
The Resource Settings API allows users to control and modify the behavior of
their GCP resources (e.g., VM, firewall, Project, etc.) across the Cloud
Resource Hierarchy.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future... |
from re import findall
from setuptools import setup, find_packages
__description__ = '''
A package to help you setting up new projects with a fitting environment.
You have an idea, get coding lickety split!
'''
meta_file = open("licketysplit/metadata.py").read()
metadata = dict(findall("__([a-z]+)__\s*=\s*'([^']+)'... |
#vision.py
import io
import os
from dotenv import load_dotenv
from google.cloud import vision
from google.cloud.vision import types
#from oauth2client.service_account import ServiceAccountCredentials
load_dotenv() # load implicit creds GOOGLE_APPLICATION_CREDENTIALS
#
## SETUP
#
def new_client():
##credentials ... |
from panda3d.core import PNMImage, Texture, LVecBase3d, NodePath, Shader
from panda3d.core import ShaderAttrib, LVecBase2i, Vec2
from ..DebugObject import DebugObject
from ..Globals import Globals
import math
class GPUFFT(DebugObject):
""" This is a collection of compute shaders to generate the inverse
ff... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 12:06:48 2018
@author: geiger
"""
from optics_calcs.refrIndexData import RefrIndexData
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
class Material:
def __init__(self,name):
#get wavelength and re... |
import os
import smtplib
from dataclasses import dataclass
from email.message import EmailMessage
from email.utils import formataddr
import requests
from aws_xray_sdk.core import xray_recorder
from coworks import Blueprint, FileParam, entry, MicroServiceProxy
from coworks.context_manager import XRayContextManager
#... |
"""
Example on how to write custom sampling menthod using the base class
This example will be moved to the documentation
"""
from f3dasm.doe.sampling import SamplingMethod
from numpy.core.records import array
import numpy as np
class MyCustomeSampling(SamplingMethod):
# write custome sampling method to the 'compute_... |
"""Mask transformation functions."""
import copy
import numpy as np
import mxnet as mx
from ..mscoco.utils import try_import_pycocotools
__all__ = ['flip', 'resize', 'to_mask', 'fill', 'crop', 'expand', 'proto_fill']
def flip(polys, size, flip_x=False, flip_y=False):
"""Flip polygons according to image flipping d... |
## Simple schematic of task timing
"""
1H
TRIAL_TIMELINE
N/A
Trial timeline
"""
import numpy as np
import matplotlib.pyplot as plt
import my.plot
my.plot.manuscript_defaults()
my.plot.font_embed()
## CONSTS
# Distances
CLOSE_DISTANCE = 5.5 # np.sqrt(2 * 4**2)
MED_DISTANCE = CLOSE_DISTANCE + 2.7
FAR_DI... |
from setuptools import setup, find_packages
import re, os
on_rtd = os.getenv('READTHEDOCS') == 'True'
requirements = []
with open('requirements.txt') as f:
requirements = f.read().splitlines()
readme = ''
with open('README.md', encoding='utf-8_sig') as f:
readme = f.read()
setup(name='pya3rt',
author=... |
from schematics import Model
from schematics.types import ModelType, ListType, StringType, IntType, DateTimeType, BooleanType, FloatType, DictType, UnionType, MultiType
class Labels(Model):
key = StringType()
value = StringType()
class View(Model):
use_legacy_sql = BooleanType(deserialize_from='useLegac... |
# coding=utf-8
from future import standard_library
standard_library.install_aliases()
#!/usr/bin/env python
from unittest import TestCase
from urllib.parse import urlparse
from monitorrent.plugins.trackers import TrackerSettings
from monitorrent.plugins.trackers.unionpeer import UnionpeerOrgTracker
from tests import us... |
def get_cart(session):
'''
Given a Django session, if the cart exists, return it;
otherwise return an empty cart.
'''
if 'cart' not in session:
session['cart'] = {}
return session['cart']
|
# -*- coding: utf-8 -*-
from . import test_event_flow, test_mail_schedule
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Alexandru Bleotu <alexandru.bleotu@morganstanley.com>`
Tests for cluster related functions in salt.utils.vmware
'''
# Import python libraries
from __future__ import absolute_import
import logging
# Import Salt testing libraries
from salttesting import TestCase, skipIf
... |
import MySQLdb as mdb
from SQLManager import SQLManager
__author__ = 'pedro'
class MySQLManager(SQLManager):
def __init__(self, host, login, password, database):
# Create the basic database configuration
self.host = host
self.login = login
self.password = password
self.dat... |
"""Actuator disc momentum theory functions.
Notes:
area is the effective area of the actuator disc.
disc_efficiency, induced_power/shaft_power, is the efficiency of shaft power
adding momentum to the flow in the useful (i.e. axial) direction,
which captures losses from effects such as swirl and viscosity. Default
dis... |
import yaml
import os
import sys
import time
import csv
from datetime import datetime
import numpy as np
import cv2 as cv
import gripper_control as gripper
from realsense_wapper import realsense
from franka.FrankaController import FrankaController
from get_obj_by_color import get_obj_bbox, check_gripper_bbox
def re... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: steammessages_clientserver.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 import message as _message
from google.protobuf import r... |
import sys
sys.setrecursionlimit(10**6) |
# The MIT License
#
# Copyright 2015 UB Bochum <bibliographie-ub@rub.de>.
#
# 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
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.