content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Mon Jan 22 07:11:20 2018
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.sta... |
import operator
import os
import pyjsonrpc
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import mongodb_client
PREFERENCE_MODEL_TABLE_NAME = "user_preference_model"
SERVER_HOST = 'localhost'
SERVER_PORT = 5050
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) ... |
# Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from dateutil import parser
alphanumeric = RegexValidator(r'^[0-9a-zA-Z_]*$', 'Only alphanumeric chara... |
# B2083-画矩形
try:
a, b, c, f = (input().split())
except:
a, b, c, f = (17, 92, '1', 0)
a, b = int(a), int(b)
try:
f = int(f)
if f != 0:
f = 1
except:
f = 0
if f == 0:
print(c * b)
for i in range(a - 2):
print(c + ' ' * (b - 2) + c)
print(c*b)
else:
fo... |
from neuron.neuron import Neuron
import numpy as np
class NeuronBuilder:
zero_quantization_error = None
def __init__(self, tau_2, growing_metric):
self.__growing_metric = growing_metric
self.__tau_2 = tau_2
def new_neuron(self, weights_map, position):
assert self.zero_quantizatio... |
import pandas as pd
import numpy as np
# event_start_with = ['underwater', 'sochi', 'varoufakis',
# 'sandy', 'samurai', 'pigFish',
# 'nepal', 'passport', 'malaysia',
# 'livr', 'garissa', 'elephant',
# 'eclipse', 'columbianChemicals', 'brin... |
from .birthday import *
from .checks import *
from .cooldown import *
from .filter import *
from .permissions import *
from .transformers import * |
import unittest
import os
import secrets
import sys
sys.path.append("..")
from wrapmail.gmail.email import Gmail
class GmailTest(unittest.TestCase):
def setUp(self):
self.html_template = "test_html_temp.html"
self.pdf_attachment = "test_pdf_attach.pdf"
self.from_mail = os.environ.get("EMAI... |
import unittest
import numpy as np
from desispec.spectra import Spectra
from desispec.io import empty_fibermap
from desispec.coaddition import coadd,fast_resample_spectra,spectroperf_resample_spectra
from desispec.maskbits import fibermask
class TestCoadd(unittest.TestCase):
def _random_spectra(self, ns=... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# Coffee machine options : latte (200 mL water + 2 g coffee + 15 ml milk), espresso (50 ml water + 18 g coffee), cappuccino (250 ml water + 24 g coffee + 100 ml milk)
# Different prices (espresso = 1.50, latte = 2.50, cappuccino = 3.00)
# hardware : Water inlet, coin slot, ADD contactless, coin acceptor, LCD display, d... |
class LibraError(Exception):
pass
class AccountError(LibraError):
pass
class TransactionError(LibraError):
@property
def error_code(self):
code, _ = self.args
return code
@property
def error_msg(self):
_, msg = self.args
return msg
class Adm... |
import databases
import sqlalchemy
from fastapi import FastAPI
from fastapi_users import models
from fastapi_users.db import OrmarBaseUserModel, OrmarUserDatabase
class User(models.BaseUser):
pass
class UserCreate(models.BaseUserCreate):
pass
class UserUpdate(User, models.BaseUserUpdate):
pass
class... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Базовый пример."""
from balaboba import balaboba
response = balaboba("Привет")
print(response)
|
def assign_ROSCO_values(wt_opt, modeling_options, control):
# ROSCO tuning parameters
wt_opt['tune_rosco_ivc.PC_omega'] = control['pitch']['PC_omega']
wt_opt['tune_rosco_ivc.PC_zeta'] = control['pitch']['PC_zeta']
wt_opt['tune_rosco_ivc.VS_omega'] = control['torque']['VS_omega']
wt_o... |
import pandas as pd
import numpy as np
import pytest
from column_completer import ColumnCompleter
X = np.random.randint(0, 100, (8, 3))
def test_name_collision_value_error_1():
df = pd.DataFrame(X, columns=["Col A", "Col_A", "Col B"])
with pytest.raises(ValueError) as err:
q = ColumnCompleter(df)
... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
from django.views.generic import CreateView, UpdateView, ListView
from .forms import MultipleChoiceTestWithAnswersForm
from .models import *
from django.utils.decorators import method_decorator
from JustTesting.utils.permission_decorators import user_permissions_decorator
@method_decorator(user_permissions_decorator,... |
# -*- coding: utf-8 -*-
from ....Classes.Circle import Circle
from ....Classes.Arc1 import Arc1
from ....Classes.Segment import Segment
from ....Classes.SurfLine import SurfLine
from numpy import exp, pi
from ....Functions.labels import (
SHAFT_LAB,
NO_LAM_LAB,
BOUNDARY_PROP_LAB,
SHAFTSR_LAB,
SHAFTS... |
# -*- coding: utf-8 -*-
# @Author: liangou
# @Date: 2021-02-25 12:39:08
# @Last Modified by: liangou
# @Last Modified time: 2021-04-18 16:32:48
# -*- coding: utf-8 -*-
# @Author: liangou
# @Date: 2021-01-25 22:08:08
# @Last Modified by: liangou
# @Last Modified time: 2021-02-22 20:53:50
import pandas as pd
imp... |
import numpy as num
from random import randrange
from scipy.sparse.linalg import gmres
import matplotlib.pyplot as plt
import math
import datetime
# gmmres with givens rotation
#givens rotation
def gmres_algorithm_givens (A , b , x0 , error , max_iter ):
res = b - num.asarray(num.dot(A,x0)).reshape(-1) # r... |
import os
from rasa.core.test import _generate_trackers, collect_story_predictions, test
# we need this import to ignore the warning...
# noinspection PyUnresolvedReferences
from rasa.nlu.test import run_evaluation
from tests.core.conftest import (
DEFAULT_STORIES_FILE,
E2E_STORY_FILE_UNKNOWN_ENTITY,
END_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-12-25 16:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('rules', '0001_initial'),
]
ope... |
from hanspell import spell_checker
from hanspell.constants import CheckResult
if __name__ == '__main__':
for i in range(1) :
result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다. 외않되. 잘 되는데?')
#print(type(result))
#print(result.as_dict().get("original"))
#pri... |
class Squaring:
@staticmethod
def squaring(a):
c = a * a
return c |
'''
======================================================
Plotting a linear function with a categorical variable
======================================================
Fitting a pyearth model to a linear function shows that pyearth
will automatically choose a linear basis function in some cases.
'''
import numpy as ... |
from flaskapp import start_flask_server
flask_server = start_flask_server()
if __name__ == "__main__":
flask_server.run(debug=True,host='0.0.0.0')
|
import numpy as np
import cv2
import imutils
import glob
import math
import os
from db_config import *
session,engine = connect_db()
from config import *
import ot_functions as ot
def capture_plate(path,plate_name):
'''
Activates the webcam and streams its feed until you press 'q' on the keyboard
while on... |
import re
from django.core.cache import caches
from django.template.loader import render_to_string
from django.core.paginator import Paginator
from moex.utils import (search_new_securities_api,
security_search_in_db,
add_search_securities_to_cache)
from ..types_classes... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy import genfromtxt
import seaborn as sns
#### ANN (FULL) ####
######################
# TAKES A FEW HOURS! #
######################
mcruns = 100000
df_ANN_fullvar = pd.DataFrame() # x scenarios, y mc runs per scenario
i = ... |
import os
cwd=os.getcwd()
global path
from pydub import AudioSegment
from pydub.playback import play
path_terminator='/home/pi/Desktop/terminator_soundboards/'
path_starwars='/home/pi/Desktop/StarWars_audio'
def play_Strong_with_the_force():
path_i=os.path.join(path_starwars,'Strong with the force.mp3')
sound =... |
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from constants import *
from nodesensordisplay import NodeSensorDisplay
from scipy.optimize import minimize
import csv
import math
import numpy as np
import cv2
#Defines direction of arrow to render for each robo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/6 19:12
# @Author : CoderCharm
# @File : __init__.py.py
# @Software: PyCharm
# @Desc :
"""
测试用例
官网地址
https://fastapi.tiangolo.com/tutorial/testing/
主要使用 TestClient 模块测试
from fastapi.testclient import TestClient
继承了 requests
TestClient(requests... |
from functools import singledispatch
@singledispatch
def getMax(number):
return number
@getMax.register
def _(number1, number2): # Compares two numbers and returns the bigger one
if(number1 > number2):
result = number1
else:
result = number2
return result
@getMax.register
def _(number... |
"""
Create a “LunarCalendarUtils” class that have ability to convert from Gregorian calendar to Lunar Calendar
"""
|
from torch.utils import data
from torchvision import datasets, transforms
def get_dataset(dataset, aug):
avail_datasets = {
'cifar10': get_cifar10,
'cifar100': get_cifar100
}
assert dataset in avail_datasets
return avail_datasets[dataset](aug)
# credits: https://github.com/kuangliu/pyt... |
import sqlite3
#中文繁简转换工具,Musicbrainz数据库中文均为繁体
from zhconv import convert
# Replace your own parameters
mbdump_path='mbdump/'
database_path='db.sqlite3'
prefix='musicbrainz_'
# Connect to the database
connection = sqlite3.connect(database_path)
'''
#Custom database table names .
# You may need to change table names ... |
"""
This file houses all of the digging functionality
@created: 11-1-2020
"""
import odrive
from odrive.utils import dump_errors
from odrive.enums import *
import subprocess
import yaml
import time
class Digging:
#--------------------------------------------------------------------
# Digging initialize funct... |
import unittest
import logging
from flask import jsonify
from app.app import app
from app.utils.logger_wrapper import setup_logging
setup_logging()
logger = logging.getLogger(__name__)
class FlaskrTestCase(unittest.TestCase):
API_PREFIX = '/v1'
def setUp(self):
logger.info('Setting up for the test ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Ricardo Ribeiro"
__credits__ = ["Ricardo Ribeiro"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
__status__ = "Development"
from __init__ import *
import random, time
f... |
#!/usr/bin/python
#-------------------------------------------------------------------------------
# Copyright 2019 Pivotal Software 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
#
#... |
#!/usr/bin/env python3
#
from __future__ import division, print_function
import numpy as np
class Transformation(object):
"""
Transforms from model to search space (and back).
"""
def transform(self, parameters, which_model, no_cells):
"""
Transform from model into search space.
... |
#!/usr/bin/env python3
# coding: utf-8
import re
import sys
import json
from typing import Optional
import requests
from retrying import retry
headers = {
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0',
}
# Testing ID - Alway... |
import sys
from functools import partial
import unittest, pytest
import sympy as sp
import matplotlib.pyplot as plt
if sys.platform == 'win32':
pytestmark = pytest.mark.skip("Skipping test on Windows")
dl = None
skiptest = unittest.skipIf(
True, reason="fenics_adjoint package not available on Wi... |
class QuickProtocol:
def __init__(self):
self.functions = dict()
def handle(self, query):
function_name = query["function"]
if function_name not in self.functions:
query.add_error("function {} not found".format(function_name), code=404)
return
func = self... |
import logging
from pyFeatSel.FeatureSelectors.FeatureSelector import FeatureSelector
from pyFeatSel.misc.Helpers import create_all_combinations
class CompleteFeatureSpace(FeatureSelector):
def run_selecting(self):
column_names = self.train_data.columns.values.tolist()
combns = [comb for comb i... |
#!/bin/python
import os
from os import path
import sys
import argparse
import platform
import subprocess
import logging
import xml.etree.ElementTree as ET
logfile = None
if os.environ.get('VTEST_PY_VENV_PATH'):
logfile = os.environ['VTEST_PY_VENV_PATH'] + '/run_test.log'
else:
logfile = os.path.realpath(
... |
from itertools import product
from random import sample
import math
import numpy as np
from PyR2 import hu
from robotics.pyr2.utils import get_box_body
from PyR2.pr2.pr2Robot import makeRobot
BODY_PLACEMENT_Z_OFFSET = 1e-3
TOP_HOLDING_LEFT_ARM = [0.67717021, -0.34313199, 1.2, -1.46688405, 1.24223229, -1.95442826, 2.... |
import autoslug.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Email",
fields=[
(
"id",
models.AutoField(
... |
"""Implementation of the spreadplayers command."""
from mcipc.rcon.be.types import RelativeFloat
from mcipc.rcon.client import Client
__all__ = ['spreadplayers']
# pylint: disable=C0103,R0913
def spreadplayers(self: Client, x: RelativeFloat, y: RelativeFloat,
spread_distance: float, max_range: fl... |
import toppra
import pytest
try:
import openravepy as orpy
IMPORT_OPENRAVE = True
except ImportError as err:
IMPORT_OPENRAVE = False
except SyntaxError as err:
IMPORT_OPENRAVE = False
@pytest.fixture(scope="session")
def rave_env():
env = orpy.Environment()
yield env
env.Destroy()
def py... |
from gpiozero import Motor
from time import sleep
import sys, select, tty, termios
motorA = Motor(17,18)
motorB = Motor(22,23)
def isData():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
i = 0
... |
"""
Testing the brand new datasets from tensorflow community for experimenting on
ImageNet2012 dataset.
We identify several problems while working with ImageNet dataset:
1. The dataset is not easy to download. Credentials (email) of some well known
organization/university is required to get the dowanload link.
2. The h... |
import unittest
import datetime
import dwetl
from dwetl.reader.list_reader import ListReader
from dwetl.writer.list_writer import ListWriter
from dwetl.job_info import JobInfo
from dwetl.processor.ezproxy_processor import EzproxyProcessor
from tests import test_logger
import logging
import pdb
import pprint
class Tes... |
import asyncio
import binascii
import contextlib
import io
import time
from unittest import TestCase, skipIf
from aioquic import tls
from aioquic.buffer import UINT_VAR_MAX, Buffer, encode_uint_var
from aioquic.quic import events
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection imp... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1719-Number-Of-Ways-To-Reconstruct-A-Tree.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-02-16
==============... |
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC
from scipy.linalg import eig
class JDA:
'''
Implements Joint Distribution Adaptation.
To read ... |
#WITH SET
def get_string_permutations(input_string):
if len(input_string) < 1:
raise ValueError('Input cannot be an empty string')
elif len(input_string) == 1:
return set(input_string)
return generate_permutations(get_string_permutations(input_string[:-1]), input_string[-1])
def generate_p... |
# -*- coding: utf-8 -*-
'''
Project Birdseye server source package. Requires gevent greenlet patch.
'''
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_rq2 import RQ
import logging.config
import sys
def _get_version():
try:
import birdseye.version # pragma: no cover
ret... |
import pathlib
import spacy
from spacy.matcher import Matcher
root_dir = pathlib.Path(__file__).parent.parent
nlp = spacy.load(f"{root_dir}/models/pt_core_news_sm_addresses")
# TODO verificar melhor maneira de identificar abreviações
LOCATION_LABELS = ["STATE", "ZIPCODE"]
# adiciona identificação de ce... |
#!usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'yanqiong'
import base64
import ctypes
import hashlib
import logging
import os
from pathlib import Path
import sys
import uuid
from typing import Optional
from tqsdk.tradeable.otg.base_otg import BaseOtg
from tqsdk.tradeable.mixin import FutureMixin
class Tq... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from setuptools import setup
with open('mapmaker/__init__.py') as f:
for line in f:
if line.startswith('__version__'):
VERSION = line.split('\'')[1]
break
with open('requireme... |
'''
#装饰器
视图函数应用验证装饰器:
1.在视图函数之前@ValidateDecorator()
2.定义_validate_function(request,context)
3.在_validate_function中验证各个字段
@ValidateDecorator()
def function(request):
id = request.POST['id']
return render_to_response('')
#验证方法以 _validate_ 做前缀
def _validate_function(request, context):
if not context.validate... |
from django.core.exceptions import ImproperlyConfigured
import random
from .arm_wells_support.models import Story
from ._utils import add_n_random_stories_to_well
from ._utils import generate_random_story
from ._utils import generate_random_well
from ._utils import TestCase
from ..views import SimpleWellView
from ..v... |
from gamepack.equipment.Equipment import Equipment
from gamepack.inventory.Inventory import Inventory
from gamepack.moneypouch.MoneyPouch import MoneyPouch
class Player(object):
def __init__(self, name = ''):
self.name = name
self.health = 100
self.defense = 1
self.equipment = Equ... |
"""
A validator for a frontend failure model. The model contains all
the failing web frontends and their status, as well as the virtual
machines they run on.
"""
from vuluptuous import Schema
schema = Schema({
'web_frontends_failures'
})
|
class Question:
'This container Class stores information about a single question'
def __init__(self, dicVal):
self.answer_time = dicVal['answer_time']
self.cat_name = dicVal['cat_name']
self.question_id = dicVal['q_id']
self.timestamp = dicVal['timestamp']
self.cat_i... |
import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_ENTITY_ID
import voluptuous as vol
DOMAIN = "setter"
SERVICE_DELETE = "delete"
SERVICE_DELETE_SCHEMA = vol.Schema({vol.Required(CONF_ENTITY_ID): cv.entity_id})
SERVICE_SET = "set"
SERVICE_SET_SCHEMA = vol.Schema(
{
... |
"""
pipeline
~~~~~~~~
This module defines pipeline and combining transformations,
which combine multiple ciphers together to form a complex cipher.
The encryption and decryption algorithms are pipelined to produce
the overall encryption and decryption effect.
- Classes
- Pipeline:... |
import io
import pickle
from contextlib import closing
import click
from matplotlib import pyplot as plt
import networkx as nx
import pydot
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import Session
from views_query_planning import query_planning, compose_join, query_with_ops
@click.group(name... |
from django.db import models
from django.contrib.auth.models import User
class account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
auth_id = models.CharField(max_length=40)
username = models.CharField(max_length=30)
def __str__(self):
return self.username
cla... |
from django.shortcuts import render, get_object_or_404
from django.template.loader import render_to_string
from django.http import JsonResponse
from django.views import View
from elasticsearch_dsl.query import Q
from cms_pages.models import NewsPageTag
from catalog.models import Address, Ownership
from catalog.api im... |
"""
Capstone Project. Code to run on the EV3 robot (NOT on a laptop).
Author: Your professors (for the framework)
and Marcus Hughes-Oliver
Winter term, 2018-2019.
"""
import rosebot
import mqtt_remote_method_calls as com
import time
import shared_gui_delegate_on_robot
def main():
"""
This code, w... |
import argparse
import logging
import os
import anndata
import numpy as np
import pandas as pd
import scipy.sparse
from cirrocumulus.anndata_util import get_scanpy_marker_keys, datasets_schema, DataType
from cirrocumulus.io_util import get_markers, filter_markers, add_spatial, SPATIAL_HELP, unique_id
from cirrocumulu... |
import ROOT as r
from glob import glob
from os import path, makedirs
from argparse import ArgumentParser
r.gSystem.Load('libFramework.so')
def main():
# Parse
parser = ArgumentParser()
parser.add_argument('-i', dest='infile')
parser.add_argument('-o', dest='outdir')
args = parser.parse_args()
... |
"""
Script that listens for user input.
"""
from gpiozero import LED
from time import sleep
red = LED(17)
while True:
red.on()
sleep(1)
red.off()
sleep(1)
|
BOT_TOKEN = "1629027959:AAEaTw4s2qaAL3mYP3fQRnE"
RESULTS_COUNT = 4 # NOTE Number of results to show, 4 is better
SUDO_CHATS_ID = [-1001477025068, -1001440596979]
DRIVE_NAME = [
"Root", # folder 1 name
"Cartoon", # folder 2 name
"Course", # folder 3 name
"Movies", # ....
"Series", # ......
... |
# Copyright (c) Moshe Zadka
# See LICENSE for details.
extensions = ['sphinx.ext.mathjax']
master_doc = 'index'
project = 'Calculus 101'
copyright = 'Copyright (c) 2015, Moshe Zadka'
author = 'Moshe Zadka'
latex_elements = dict(preamble='\usepackage{amsfonts}\n')
|
import tensorflow as tf
def custom_model():
inputs = tf.keras.layers.Input(shape=(4, 1), name="input")
x = tf.keras.layers.Flatten()(inputs)
outputs = tf.keras.layers.Dense(3, name="output")(x)
return tf.keras.Model(inputs=inputs, outputs=outputs, name="simple-model")
def loss(labels, predictions):
... |
from xml.etree.ElementTree import ElementTree
import numpy as np
import pytest
from deepocr.io import elements
def _mock_words(size=(1., 1.), offset=(0, 0), confidence=0.9):
return [
elements.Word("hello", confidence, (
(offset[0], offset[1]),
(size[0] / 2 + offset[0], size[1] / ... |
from django.conf.urls import patterns, include, url
from art import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='art'),
url(r'^audit/$', views.ArtAuditView.as_view(), name='audit'),
url(r'^upload/$', views.UploadTaskView.as_view(), name='upload'),
url(r'^up_upload/$', views.Upd... |
'''
Convert_Sticky.py
Copyright (c) 2003 - 2006 James Urquhart(j_urquhart@btinternet.com)
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 rig... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
##################################################################################
# File: c:\Projects\KENYA ONE PROJECT\CORE\engines\Gudmundsson_Constraint.py #
# Project: c:\Projects\KENYA ONE PROJECT\CORE\engines #
# Created Date: Thur... |
class Solution:
def lengthOfLongestSubstring(self, s):
unique = set()
left = 0
right = 0
maxi = 0
while right < len(s):
if s[right] not in unique:
unique.add(s[right])
right+=1
maxi = max(maxi, len(unique))
... |
import logging
import os
import re
from subprocess import run, CalledProcessError # nosec
if __name__ == '__main__':
ignored_patterns = [
'setup.py',
'build',
'tools',
'projects',
'.history',
'torchreid/models',
'torchreid/data',
'torchreid/engine',... |
import math, random
import pygame, time
import tkinter as tk
from src.Environment.variables import START1, START2, END1, END2, START_REWARD, BEST_REWARD
from src.Grid.node import Node
# Multi-agent Environment
# Get the start and end node for each agent and insert them to the grid
def start_end_pos(grid, width, tota... |
# 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... |
from .reg.linear_regression import LinearRegression
from .reg.k_nearest_neighbour import KNNReg
from .classi.k_nearest_neighbour import KNNClassi
__all__ = ['LinearRegression', "KNNReg", 'KNNClassi']
|
from .token import Token, TokenType
from .tokenizer import Tokenizer
|
def exponentation(base_number, exponent):
# watch out: 0^0 is defined as 1 (as indicated by Google Calculator)
if exponent == 0:
return 1
else:
return base_number * exponentation(base_number, exponent - 1)
if __name__ == "__main__":
n_a_1 = 3
n_a_2 = 4
print("Input numbers:", n... |
from test.helper import (
execute_add,
wait_for_process,
command_factory,
)
def test_kill_remove_resume(daemon_setup):
"""Old `done` and `failed` entries will be deleted."""
# Add a command that fails, and finishes as well as queued and running processes
execute_add('failingstufftest')
ex... |
def send_GET(sock:dict) -> dict:
blob = [sock[bob] for bob in sock]
sock = blob[2]
headers_ = ("GET /%s HTTP/1.1\r\x0AHost: %s\r\x0AAccept: */*\r\x0AConnection: close\r\x0AUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36\r\x0A\r\x0A"%(b... |
# -*- coding: utf-8 -*-
"""@package scrape
@date Created on nov. 15 09:30 2017
@author samuel_r
"""
def get_translation(jp_text):
return
|
#!/usr/bin/env python
import io
import struct
import os
import re
from datetime import datetime, timedelta
import sys
from tqdm import tqdm
__author__ = 'petercable'
datere = re.compile('(\d{8}T\d{4}_UTC)')
binary_sync = '\xa3\x9d\x7a'
file_scan_depth = 256000
def lrc(data, seed=0):
for b in bytearray(data):
... |
# -*- coding: utf-8 -*-
class CMSApp(object):
name = None
urls = None
menus = []
app_name = None
|
import numpy as np
import pylot.utils
from pylot.perception.detection.utils import BoundingBox2D, BoundingBox3D, \
get_bounding_box_in_camera_view
VEHICLE_LABELS = {'car', 'bicycle', 'motorcycle', 'bus', 'truck', 'vehicle'}
class Obstacle(object):
"""Class used to store info about obstacles.
This class... |
from flask import Flask, request, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from flask_wtf.csrf import CSRFProtect
from flask_login import LoginManager
from flask_mail import Mail
from datetime import datetime
from flask_login import UserMixin
impo... |
import hashlib
import json
from typing import Any, Callable, List
from clvm import SExp
OpCallable = Callable[[Any, "ValStackType"], int]
ValStackType = List[SExp]
OpStackType = List[OpCallable]
def sha256tree(v):
pair = v.as_pair()
if pair:
left = sha256tree(pair[0])
right = sha256tree(p... |
from typing import List
from Yacht.Dice import Dice
from Yacht.PointTable import PointTable
from Yacht.PointType import PointType
class Player:
point_table: PointTable = PointTable()
dices: List[Dice] = [Dice(), Dice(), Dice(), Dice(), Dice()]
roll_count: int = 0
def __init__(self):
self.poi... |
"""Support for interface with an Samsung TV."""
import asyncio
from datetime import timedelta
import logging
import socket
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
MEDIA_TYPE_CHANN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.