content stringlengths 5 1.05M |
|---|
from dagster import repository
from src.pipelines.ingest import ingest_pipeline
from src.pipelines.populate_dm import populate_dm_pipeline
from src.pipelines.asset_experimentation import asset_experimentation
@repository
def software_releases_repository():
"""
The repository definition for this newp Dagster ... |
import numpy as np
import torch
def snr(S, N):
'''
Returns the signal to noise ratio for
@param S: the signal
@param N: the noise
'''
temp = 20 * np.log10(1 + np.linalg.norm(np.squeeze(S), axis=(1, 2)) /
np.linalg.norm(np.squeeze(N), axis=(1, 2)))
# filter inf valu... |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db.models import Sum, Q
from django.db.models.functions import Coalesce
from django.utils import timezone
from djmoney.money import Money
from decimal i... |
# -*- coding: utf-8 -*-
"""
HydroView-Flask
~~~~~~
Python Flask version of HydroView with Apache Cassandra as backend.
"""
import logging
import os
import sys
from flask import Flask
from cassandra.cluster import Cluster
from cassandra.query import dict_factory
from cassandra_udts import Avera... |
class Vector:
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
def _sqrt(self, x):
if x < 0:
raise ValueError('x < 0')
return x**0.5
def __add__(self, vec):
return Vector(self.x+vec.x, self.y+vec.y, self.z+vec.z)
... |
# -*- coding: utf-8 -*-
"""
Drift game server management - S3 Functionality
------------------------------------------------
"""
import os
import os.path
from zipfile import ZipFile
import subprocess
import shutil
import time
import socket
import json
from functools import wraps
import sys
import random
import ... |
from django.contrib.auth import views as auth_views
from django.urls import path
from .views import register, profile
urlpatterns = [
path("register/", register, name="register"),
path("profile/", profile, name="profile"),
path(
"login/",
auth_views.LoginView.as_view(template_name="users/u... |
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
import math
import os
import pynvml
pynvml.nvmlInit()
def systemGetDriverVersion():
r"""Get Driver Version"""... |
import sys
import numbers
try:
print("read file: \t" + str(sys.argv[1]))
print("write file: \t" + str(sys.argv[2]))
print("reference file: \t" + str(sys.argv[3]))
filenamer = str(sys.argv[1])
filenamew = str(sys.argv[2])
filenameref = str(sys.argv[3])
fr = open(filenamer, 'r')
fref = open(filenameref, 'r')
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from urllib.parse import urlparse
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mariadb://root:password@localhost:3306/ant... |
# Generated by Django 2.2.5 on 2019-11-19 14:57
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("workflow_handler", "0002_auto_20191119_1457"),
]
operations = [
migrations.AlterField(
model_na... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2020 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
Test against issue #16.
<https://github.com/heuer/segno/issues/16>
"""
from __future__ import unicode_literals, absolute_import
import segno
def test_boost_error_automatic():
qr = segno.make_... |
"""
Know What You Don’t Know: Unanswerable Questions for SQuAD
https://arxiv.org/pdf/1806.03822.pdf
Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset,
consisting of questions posed by crowdworkers on a set of Wikipedia articles,
where the answer to every question is a segment of text... |
ImporteAPagar = float(input("Cuanto pagas?"))
importeCoste = float(input("Cuanto cuesta?"))
importeDevolucion = ImporteAPagar-importeCoste
# print(importe)
# importes de los billetes y monedas con su tipo en singular
tipos = (
(500, "billete"),
(200, "billete"),
(100, "billete"),
(50, "billete"),
... |
#!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright 2014 Esri
# 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.apac... |
import os
import unittest
from supervised.tuner.mljar_tuner import MljarTuner
class TunerTest(unittest.TestCase):
def test_key_params(self):
params1 = {
"preprocessing": {"p1": 1, "p2": 2},
"learner": {"p1": 1, "p2": 2},
"validation_strategy": {},
}
para... |
"""Representation base class."""
from abc import ABC, abstractmethod
from copy import deepcopy
import logging
import numpy as np
from rlpy.tools import bin2state, closestDiscretization, hasFunction, id2vec, vec2id
import scipy.sparse as sp
from .value_learner import ValueLearner
__copyright__ = "Copyright 2013, RLPy h... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
# Output C #defines for errors into wiredtiger.in and the associated error
# message code in strerror.c.
import re, textwrap
import api_data
from dist import compare_srcfile
# Update the #defines in the wiredtiger.in file.
tmp_file = '__tmp'
tfile = open(tmp_file, 'w')
skip = 0
for line in open('../src/include/wired... |
'''
@author: mtmoncur
@Link: https://github.com/mtmoncur/deepracer_env
@License: MIT
'''
def reward_function(params):
"""
Available option:
all_wheels_on_track (bool)
True if car is on track, False otherwise
x (float)
x coordinate in meters
y (float)... |
from sqlalchemy import Column, Table, Integer, String, create_engine
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
Base = declarative_base()
Session = sessionmaker()
class Post(Base):
__tablename__ = 'post'
__ta... |
#!/usr/bin/env python3
import sys
print("Hello world!")
sys.exit(0)
|
import matplotlib.pyplot as plt
import numpy as np
import os
plt.style.use(['science','ieee','grid', 'no-latex'])
def savefig(x, y, dirname="./fig", name="test.svg"):
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot(x, y)
dirname = os.path.join(dirname, name)
fig.savefig(dirn... |
import os
from ctypes import *
import platform
STATUS_CALLBACK = CFUNCTYPE(None, c_int, c_char_p)
STATUS_CALLBACK_COUNT = CFUNCTYPE(None, c_int, c_int, POINTER(c_uint32))
class ASG8005:
_instance = None
m_CountCount = 0
py_callback = {}
def __new__(cls, *args, **kw):
if cls._instance is Non... |
"""
顺序模型
@author Aaric
@version 0.5.0-SNAPSHOT
"""
import matplotlib.pyplot as plt
import numpy as np
from keras.layers import Dense
from keras.models import Sequential
# 训练数据
x_data = np.random.random(100)
y_data_noise = np.random.normal(0, 0.01, x_data.shape)
y_data = x_data * 0.1 + 0.2 + y_data_noise
# 顺序模型
mode... |
# -*- coding: utf-8 -*-
"""
@date: 2020/10/19 下午7:39
@file: __init__.py.py
@author: zj
@description:
"""
"""
参考[Why torchvision doesn’t use opencv?](https://discuss.pytorch.org/t/why-torchvision-doesnt-use-opencv/24311)
使用[jbohnslav/opencv_transforms](https://github.com/jbohnslav/opencv_transforms)替代torchvision tra... |
import kopf
import riasc_operator.project # noqa: F401
import riasc_operator.time_sync # noqa: F401
def main():
kopf.configure(
verbose=True
)
kopf.run(
clusterwide=True,
liveness_endpoint='http://0.0.0.0:8080'
)
|
import cv2
import numpy as np
with open("yolov3.txt", 'r') as f:
classes = [line.strip() for line in f.readlines()]
colors = np.random.uniform(0, 300, size=(len(classes), 3))
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
cap = cv2.VideoCapture(0)
scale = 0.00392
conf_threshold = 0.5
nms_threshold = 0.... |
from django.db import models
import datetime
import django
def accept():
return(
(True, 'Sim'),
(False, 'Nao'),
)
# Create your models here.
class Linguagem(models.Model):
lingua = models.CharField('Lingua',max_length=30, default="Português",unique=True)
def __str__(self):
... |
import h5py
import pickle
import numpy as np
from numba import jit
from torch.utils.data import Dataset
class BindspaceSingleProbeDataset(Dataset):
""" Given an probe index, return the embedding of all / some kmers in that probe
(this step is transformer dependent)
h5_filepath (string): path to ... |
from src.GraphInterface import GraphInterface
from src.Node import Node
class DiGraph(GraphInterface):
def __init__(self):
self.Nodes= {}
self.Edges= {}
self.mc = 0
def v_size(self) -> int:
return self.Nodes.__len__()
def e_size(self) -> int:
sum=0
for ke... |
from __future__ import division
import sys
import csv
import numpy as np
import pandas as pd
from pandas import DataFrame
from classifier import *
from sklearn.metrics import confusion_matrix, roc_curve, auc
import matplotlib.pyplot as plt
from sklearn import tree
def run_analysis(data_sets, labels):
print "ROC::run_... |
'''
run multiple tasks with a command
usage:
1. modify the function define_task()
2. call run_tasks()
'''
import os
import json
import subprocess
from glob import glob
from os.path import dirname
from time import sleep
used_devices = []
def exec_cmd(cmd):
r = os.popen(cmd)
msg = r.read()
... |
from django.urls import include, re_path
from softdelete.views import *
urlpatterns = [
re_path(r'^changeset/(?P<changeset_pk>\d+?)/undelete/$',
ChangeSetUpdate.as_view(),
name="softdelete.changeset.undelete"),
re_path(r'^changeset/(?P<changeset_pk>\d+?)/$',
ChangeSetDetail.as_view(),
... |
####################
# ES-DOC CIM Questionnaire
# Copyright (c) 2017 ES-DOC. All rights reserved.
#
# University of Colorado, Boulder
# http://cires.colorado.edu/
#
# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].
####################
from djan... |
import sys
from loguru import logger
from flexget import options
from flexget.event import event
from flexget.plugin import plugins
from flexget.terminal import console
logger = logger.bind(name='doc')
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal P... |
# -*- coding: utf-8 -*-
__version__ = "0.9.9.2"
from .orm import Model, SoftDeletes, Collection, accessor, mutator, scope
from .database_manager import DatabaseManager
from .query.expression import QueryExpression
from .schema import Schema
from .pagination import Paginator, LengthAwarePaginator
import pendulum
pend... |
from torch.nn.parameter import Parameter
import torch
from torch.autograd import Function
from torch import tensor, nn
import math
import torch.nn.functional as F
import time
def test(a,b,cmp,cname=None):
if cname is None: cname=cmp.__name__
assert cmp(a,b),f"{cname}:\n{a}\n{b}"
def near(a,b): return torch.al... |
from dataclasses import dataclass
from typing import Dict, Optional, Tuple
import torch
from transformers.file_utils import ModelOutput
@dataclass
class ReOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = No... |
from sqlalchemy import Table, Column, Integer, String, BigInteger, Boolean, ForeignKeyConstraint
from cassiopeia.data import Platform
from cassiopeia.dto.spectator import CurrentGameInfoDto
from cassiopeia.dto.common import DtoObject
from .common import metadata, SQLBaseObject, map_object, foreignkey_options
class ... |
"""
@file
@brief Exceptions raised during the installation of a module
"""
class MissingPackageOnPyPiException(Exception):
"""
raised when a package is not found on pipy
"""
pass
class MissingInstalledPackageException(Exception):
"""
raised when a package is not installed
"""
pass
... |
from catboost import CatBoostClassifier
def get_CatBoostClassifier(iterations=1000, learning_rate=0.01, min_data_in_leaf=30, eval_metric='AUC', cat_features=None):
return CatBoostClassifier(
iterations=iterations,
learning_rate=0.01,
min_data_in_leaf=min_data_in_leaf,
eval_metric=e... |
SIMULTANEOUS_THREADS = 150
TIMEOUT = 7
WHOIS_THREADS = 10 |
from rotkehlchen.accounting.structures.balance import Balance
from rotkehlchen.assets.asset import EthereumToken
from rotkehlchen.assets.utils import symbol_to_asset_or_token
from rotkehlchen.chain.ethereum.interfaces.ammswap.types import EventType, LiquidityPoolEvent
from rotkehlchen.chain.ethereum.modules.balancer.ty... |
import os
from setuptools import setup
from setuptools import find_packages
# Utility function to read the README file.
# From http://packages.python.org/an_example_pypi_project/setuptools.html.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup( name = "NodeBo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import time
import codecs
import subprocess
#import contextlib
#with contextlib.redirect_stdout(None):
# import pygame.mixer
#https://stackoverflow.com/questions/49871252/saving-text-to-speech-python
import win32com.client as wincl
import win32api... |
import sklearn
from sklearn.neural_network import MLPClassifier
X = [[0, 1], [1, 0], [1, 1]]
Y = [1, 1, 0]
clf = MLPClassifier(
solver="lbfgs", alpha=1e-3, hidden_layer_sizes=(5, 2), random_state=1
)
clf.fit(X, Y)
clf.predict([[2, 2], [0, 0], [-1, -2]])
print(clf.score([[2, 2], [0, 0], [-1, -2]], [1, 0, 0]))
for c... |
# Aula 18 - 03-12-2019
# Ao receber a seguinte lista, faça um metodo que retorne cada um destes itens de forma individual
# com cabaçalho dizendo em que posição estes itens estão dentro da lista principal:
# Exemplo:
# ############# posição 0 ##################
# Agua
# mamão
# ############# posição 1 ##############... |
def min(*args, **kwargs):
temp = []
if len(args) > 1:
temp = args
else:
temp = args[0]
if len(kwargs) > 0:
for k,v in kwargs.items():
return sorted(temp,key=v)[0]
else:
return sorted(temp)[0]
def max(*args, **kwargs):
temp = []
if len(args) > 1:
temp = args
else:
te... |
import numpy as np
from vg.compat import v2 as vg
__all__ = [
"transform_matrix_for_non_uniform_scale",
"transform_matrix_for_rotation",
"transform_matrix_for_translation",
"transform_matrix_for_uniform_scale",
]
def _convert_33_to_44(matrix):
"""
Transform from:
array([[1., 2., 3.],
... |
"""
## IR Markers message id position:
[3]----[4]
| |
| |
[2]----[1]
[1] (1,1,0)
[2] (-1,1,0)
[3] (-1,-1,0)
[4] (-1,1,0)
Gate width is 0.3 m
## Left Camera info:
height: 768
width: 1024
distortion_model: "plum_bob"
D: [0.0, 0.0, 0.0, 0.0, 0.0]
K: [548.4088134765625, 0.0, 512.0, 0.0, 548.4088134765625, ... |
#Exercícios Numpy-06
#*******************
import numpy as np
arr=np.zeros(10)
arr[5]=1
print(arr) |
""" Module to access the Webhooks endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel
from ...models import (
CreateIncomingWebhookJsonBody,
CreateOutgoingWebhookJsonBo... |
from pathlib import Path
import pandas as pd
from cacp.util import to_latex
def process_comparison_result_winners_for_metric(metric: str, result_dir: Path) -> pd.DataFrame:
"""
Processes comparison results, finds winners for metric.
:param metric: comparison metric {auc, accuracy, precision, recall, f1... |
# coding: utf-8
"""
grafeas.proto
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1beta1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import... |
#Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
if __name__ == "__main__":
sourceFile='source.jpg'
targetFile='target.jpg'
... |
# coding=utf-8
"""
ENAS算法控制器模型
"""
import tensorflow as tf
import numpy as np
def build_controller_model(num_node, hidden_size, controller_temperature, controller_tanh_constant):
"""
Args:
type_embedding_dim: 节点类型嵌入维度
link_embedding_dim: 连接嵌入维度
num_node:节点总数
num_type:节点类型数量
... |
# Copyright 2021 Dakewe Biotech 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
"""
Start active players for a range of dates
"""
import os
import sys
import yahooscraper as ys
from datetime import datetime, date, timedelta
from urllib.parse import urljoin
from utils import *
# Command-line args
DATE_LIMIT = date.today() + timedelta(days=365)
NUM_DAYS_DEFAULT = 1
NUM_DAYS_MAX = 100
OPTIONAL_AR... |
"""
IO Module
===========
SCOUT's IO module is for reading and writing different volumetric image formats and preparing chunked arrays for
processing. SCOUT makes use of TIFF and Zarr file formats throughout the analysis pipeline, and the this module
is meant to consolidate these side-effecting IO operations.
"""
impo... |
'''
Python Basics with Numpy
This is a brief introduction to Python.
The script uses Python 3.
The script below is to get familiar with:
1. Be able to use iPython Notebooks
2. Be able to use numpy functions and numpy matrix/vector operations
3. Understand the concept of "broadcasting"
4. Be able to vectorize code
Let... |
#!/usr/bin/env python3
# encoding: utf-8
import flask
from werkzeug.exceptions import NotFound, InternalServerError
app = flask.Flask(__name__)
@app.route('/cats/<breed>')
def cats(breed):
"""wonky code ahead!"""
return
@app.errorhandler(404)
def not_found(e):
# shame that i have to do it like this, instead of... |
def v(kod):
if (n == len(kod)):
print(kod)
return
v(kod + '0')
v(kod + '1')
n = int(input());
v('')
|
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# A... |
#print('hello!!')
num1 = 20
num2 = 10
def multiply(num1,num2):
product = num1*num2
return product
#print (multiply(num1, num2))
#for i in range(1,11):
# print (i)
def evenindex1() -> str():
word = input('enter the word - ')
print (word)
output = ''
for i in range(len(word)):
if... |
import random
import pathlib
import os
from re import X
from shutil import copyfile
import argparse
import glob
from pathlib import Path
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]
#
def copy_files(files, input_images_path, input_labels_path, output_images_path, output_label_path):
for image_name in ... |
print("Hello EFO")
print("")
print("Final")
|
from collections import defaultdict, OrderedDict, Counter
from datetime import datetime
from functools import wraps
from html.parser import HTMLParser
from operator import attrgetter
from random import randrange, shuffle
from shutil import rmtree, make_archive
from string import ascii_letters, ascii_uppercase, digits
f... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
#!/usr/bin/python3
import itertools
T=int(input())
for t in range(T):
n=int(input())
if(n<2):
print(0)
continue
a=int(input())
b=int(input())
L=[(0, 0)]
for i in range(1, n):
S=[]
for p in itertools.product(L, [a, b]):
# print(p)
S.append((p... |
# Pongo by @blogmywiki / Giles Booth
# player B code
import radio
from microbit import *
from music import play, POWER_UP, JUMP_DOWN, NYAN, FUNERAL
a_bat = 2 # starting position of player A bat
b_bat = 2 # starting position of player B bat
bat_map = {0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
ball_x = 2 ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class NatureCNN(nn.Module):
def __init__(self, params):
super(NatureCNN, self).__init__()
n_c = params['num_in_channels']
self.cnn_head = nn.Sequential(
nn.Conv2d(n_c, 32, 8, 4),
nn.ReLU(True),
... |
#!/usr/bin/python3
import tkinter
from tkinter import *
def select():
selection = "Awesome option " + str(var.get())
label.config(text = selection)
window = Tk()
var = IntVar()
radio1 = Radiobutton(window, text = "Option 1", variable = var, value = 1, command = select)
radio1.pack( anchor = W )
radio2 = Radi... |
import pysam
import os
contig_bins = {}
outlength = {}
samfile = pysam.AlignmentFile(snakemake.input.long_bam, 'rb')
gotten_contigs = set()
maxbin = 0
outreads = {}
outbases = {}
outreads500 = {}
outbases500 = {}
for bins in os.listdir(snakemake.input.metabat_done[:-4]):
if not bins.startswith(
... |
from ..libs import Gtk
from ..window import GtkViewport
from .base import Widget
class OptionContainer(Widget):
def create(self):
# We want a single unified widget; the vbox is the representation of that widget.
self.native = Gtk.Notebook()
self.native.interface = self.interface
se... |
# -*- coding: utf-8 -*-
import pytest
from sourcelocation import FileLine
def test_equals():
x = FileLine('foo.c', 1)
y = FileLine('foo.c', 2)
assert x != y
assert x == x
assert y == y
a = FileLine('bar.c', 1)
b = FileLine('foo.c', 1)
assert a != b
|
import unittest
from calc import parse, evaluate, Stack, postfix_eval, ParseError, EvaluationError
# testcase = namedtuple("testcase", ["expression", "representation", "sum"])
testcases = [
# basic testing
("5+4", ['5', '4', '+'], 9),
("1-5", ['1', '5', '-'], -4),
("(4/2)", ['4', '2', '/'], 2),
("... |
import pygame as pygame
import math
import colors # custom file that contains constants for colors
import helpers # custom helper functions
from algorithms import a_star, dijkstra, generate_walls, draw_borders
from button import Button
from tkinter import messagebox, Tk
WIDTH = 800
# set up all buttons w... |
# ##### BEGIN MIT LICENSE BLOCK #####
#
# Copyright (c) 2020 Lukas Toenne
#
# 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 u... |
"""hw2.py
by Tianqi Fang
11/06/2019
This module has a function that creates a dataframe from a URL which points to a CSV file.
Then, it has a function called test_create_dataframe with two inputs,
a pandas DataFrame and a list of column names, that make three tests.
The function returns True if the following ... |
"""
Example ackermann_kinematic.py
Author: Joshua A. Marshall <joshua.marshall@queensu.ca>
GitHub: https://github.com/botprof/agv-examples
"""
# %%
# SIMULATION SETUP
import numpy as np
import matplotlib.pyplot as plt
from mobotpy.integration import rk_four
from mobotpy.models import Ackermann
# Set the simulation t... |
"""
Augmenters that apply to a group of augmentations, like selecting
an augmentation from a list, or applying all the augmentations in
a list sequentially
To use the augmenters, clone the complete repo and use
`from vidaug import augmenters as va`
and then e.g. :
seq = va.Sequential([ va.HorizontalFlip(),
... |
import ntpath
import os
import torch
from torch import nn
from tqdm import tqdm
from configs import decode_config
from configs.munit_configs import get_configs
from configs.single_configs import SingleConfigs
from distillers.base_munit_distiller import BaseMunitDistiller
from metric import get_fid
from utils import u... |
hiragana = "ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん"
katakana = "ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴ"
hankana = ""
suuji = "01234567890123456789"
# 日本語文字列のソート
def sort_str(string, reverse=False):
return "".join(sorted(str... |
import random
import itertools
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
# name_titles = [name.title() for... |
#!/usr/bin/env python
import sys
import chpl_mem, overrides
from utils import error, memoize
@memoize
def get():
jemalloc_val = overrides.get('CHPL_JEMALLOC')
mem_val = chpl_mem.get('target')
if not jemalloc_val:
if mem_val == 'jemalloc':
jemalloc_val = 'jemalloc'
else:
... |
"""
Module for entities implemented using the
number platform (https://www.home-assistant.io/integrations/number/).
"""
from __future__ import annotations
import logging
from typing import Any
from hahomematic.const import ATTR_HM_VALUE, HmPlatform
import hahomematic.device as hm_device
from hahomematic.entity import... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
elif not matrix[0]:
return False
elif target <= matrix[0][-1]:
... |
from django.http import HttpRequest
from math import ceil
from nltk.tokenize.regexp import RegexpTokenizer
import os
import re
from search.models import Search, Field
def url_part_escape(orig):
"""
simple encoding for url-parts where all non-alphanumerics are
wrapped in e.g. _xxyyzz_ blocks w/hex UTF-8 xx... |
from subprocess import call
"""
This file contains the class Task, currently not used (Configuration.Task is used instead)
"""
__author__ = 'Sander Krause <sanderkrause@gmail.com>'
__author__ = 'Roel van Nuland <roel@kompjoefriek.nl>'
class Task:
command = None
input = None
output = None
name = Non... |
from ...nodes.BASE.node_base import RenderNodeBase
from ...preferences import get_pref
import bpy
from bpy.props import *
def test_email(self, context):
if self.test_send:
self.process()
self.test_send = False
class RenderNodeEmailNode(RenderNodeBase):
"""A simple input node"""
bl_idnam... |
# FPRBRRZA, 10027
#
# https://adventofcode.com/2018/day/10
import sys
import numpy as np
import pprint
def printStars(starsToPrint):
# need to shift everything over to be postive
minx = min([s[0] for s in starsToPrint])
maxx = max([s[0] for s in starsToPrint])
miny = min([s[1] for s in starsToPrint])... |
D_params ={
"ID_BUFFER_SIZE":[1],
"N_TX_S": [3],
"DUR_S_MS": [8],
"N_TX_T": [2],
"DUR_T_MS": [5],
"N_TX_A": [2],
"DUR_A_MS": [5],
"CRYSTAL_SINK_MAX_EMPTY_TS" : [3],
"CRYSTAL_MAX_SILENT_TAS" : [2],
"CRYSTAL_MAX_MISSING_ACKS" : [4]
}
|
from .horizontal_spinbox import HorizontalSpinbox
__all__ = ["HorizontalSpinbox"]
|
import os
import bb
import oe.path
from swupd.utils import manifest_to_file_list, create_content_manifests
from swupd.path import copyxattrfiles
def create_rootfs(d):
"""
create/replace rootfs with equivalent files from mega image rootfs
Create or replace the do_image rootfs output with the corresponding... |
# -*- coding: utf-8 -*-
'''
Microsoft Updates (KB) Management
This module provides the ability to enforce KB installations
from files (.msu), without WSUS.
.. versionadded:: Neon
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import salt libs
import salt.utils.pla... |
import json
import sys
def load_dict(fname):
with open(fname, 'r') as fp:
data = json.load(fp)
return data
def dump_dict(fname, data):
with open(fname, 'w') as fp:
json.dump(data, fp)
def break_data(data, fname, bucket_size=5000):
num_buckets = len(data) / bucket_size
if num_bu... |
#!/usr/bin/env python
'''
Use Netmiko to enter into configuration mode on pynet-rtr2. Also use
Netmiko to verify your state (i.e. that you are currently in configuration mode).
'''
from netmiko import ConnectHandler
from getpass import getpass
from routers import pynet_rtr2
def main():
'''
Use Netmiko to ente... |
#
# @lc app=leetcode id=15 lang=python3
#
# [15] 3Sum
#
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
# Note:
# The solution set must not contain duplicate triplets.
# Example:
# Given array nums = ... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
# Approach 3: Iterative with O(1)O(1) Space . Source: https://tinyurl.com/tnwofvs
class Solution(object):
def copyRandomList(self, head):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.