content stringlengths 5 1.05M |
|---|
import random
# This lib is used to choose a random word from the list of word
# The user can feed his name
name = input("What's your Name? ")
print("Good Luck ! ", name)
words = ['education','rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse',... |
import discord
import asyncio
from stem_server_roles import HOUSING_ROLE_IDS, MAJOR_ROLE_IDS, CLASS_ROLE_IDS, GRAD_YEAR_ROLE_IDS, SPECIAL_ROLE_IDS, PRONOUN_ROLE_IDS
from discord.utils import get
from bot_helper import del_convo, get_mhom, contains_role
def merge_dict(dicts): # merges dictionaries together
z = dict... |
#!/usr/bin/env python3
"""
This module provides classes used to define a periodic structure.
"""
# adapted from original version in pymatgen version from pymatgen
import math
import collections
import itertools
from abc import ABCMeta, abstractmethod, abstractproperty
import warnings
import numpy as np
from fracti... |
"""Neural network operations."""
from __future__ import absolute_import as _abs
from ...expr import TupleWrapper
from . import _make
def conv2d(data,
weight,
strides=(1, 1),
padding=(0, 0),
dilation=(1, 1),
groups=1,
channels=None,
kernel_si... |
from django.conf.urls import patterns, url
urlpatterns = patterns('testproject.myapp.views',
url(r'^', 'home')
) |
import logging
import os
from datetime import datetime
from OTLMOW.ModelGenerator.StringHelper import wrap_in_quotes
from OTLMOW.PostenMapping.PostenCollector import PostenCollector
from OTLMOW.PostenMapping.StandaardPost import StandaardPost
class PostenCreator:
def __init__(self, postenCollector: PostenCollect... |
import numpy as np
import matplotlib.pyplot as plt
W = np.loadtxt('sol.csv', skiprows=1, delimiter=',')
# Density of solid phase
plt.figure(1)
plt.plot(W[:,0], W[:,1], linestyle='-', linewidth =0.3, color='black', marker = 'o', mew=1.0, ms=1.0)
plt.xlabel(r"$x$")
plt.ylabel(r"$\rho_s$")
plt.savefig("RHO_s.pdf")
# D... |
from google.cloud import automl
from core_engine import logger
logging = logger(__name__)
def evaluate_model(
project_id: str, region: str, model_id: str, evlauation_filter: str = ""
):
"""[Evalaute Model Summary]
Args:
project_id (str): [Unique Identifier for your Project]
region (str):... |
# https://leetcode.com/problems/flip-game/submissions/
class Solution:
def generatePossibleNextMoves(self, s):
"""
:type s: str
:rtype: List[str]
"""
out = []
for i in range(0, len(s) - 1):
if s[i:i+2] == '++': out.append(s[:i] + '--' + s[i+2:])
... |
# -*- encoding: utf-8 -*-
"""
@Author : zYx.Tom
@Contact : 526614962@qq.com
@site : https://zhuyuanxiang.github.io
---------------------------
@Software : PyCharm
@Project : deep-learning-with-python-notebooks
@File : ch0503_pretained_convnet.py
@Version : v0.1
@Time :... |
# RUN: %PYTHON %s | FileCheck %s
from mlir.ir import *
from mlir.dialects import quant
def run(f):
print("\nTEST:", f.__name__)
f()
return f
# CHECK-LABEL: TEST: test_type_hierarchy
@run
def test_type_hierarchy():
with Context():
i8 = IntegerType.get_signless(8)
any = Type.parse("!quant.any<i8<-8:7... |
from django.contrib import admin
from .models import Post, Comment, Like, Follow
# Register your models here.
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Like)
admin.site.register(Follow)
|
# -*- coding: utf-8 -*-
import json
import os
import shutil
import subprocess
import sys
import time
# environ
PYTHON27 = os.environ['PYTHON27']
ROOT = os.path.realpath(os.path.dirname(__file__))
# useful paths
LOGS_PATH = os.getenv('BROAPT_LOGS_PATH', '/var/log/bro/')
APK_LOG = os.getenv('APK_LOG', '/var/log/bro/tm... |
import argparse, os, math
from theia.channels import invert_with_alpha
from theia.image import load_from_path
from PIL import Image
def main(args):
os.makedirs(args.output, exist_ok=True)
images = load_from_path(args.input)
for (name, img) in images:
# Invert the image
if args.invert:
... |
import argparse
import numpy
def chunk(thing, size):
x = 0
out = []
for val in thing:
out.append(val)
x += 1
if x % size == 0:
yield out
out = []
x = 0
if out:
yield out
if __name__ == '__main__':
parser = argparse.A... |
from functools import lru_cache
import menpo.io as mio
import menpo3d.io as m3io
import numpy as np
# load the maps between LSFM/Basel etc
@lru_cache()
def map_tddfa_to_basel():
maps = mio.import_pickle(
'/vol/atlas/databases/itwmm/mapping_mein3d_to_tddfa.pkl.gz')
return maps['map_tddfa_to_basel']
d... |
import pandas as pd
submission = pd.read_csv(
"/data/zhaoxinying/code/rsna-miccai-2021/user_data/preds/submission.csv",
index_col="BraTS21ID")
ids = [1, 13]
print(ids)
y_pred = [0.8, 0.6]
preddf = pd.DataFrame({"BraTS21ID": ids, "MGMT_value": y_pred})
preddf = preddf.set_index("BraTS21ID")
submis... |
"""
Conjuntos - Referência a teoría dos conjuntos em Matématica
#Forma 1
s = set({1, 2, 3, 4, 5, 5, 6, 7, 2, 3})
print(s)
print(type(s))
#Forma 2
s = set({1, 2, 3, 4, 5, 5})
print(s)
print(type(s))
s1 = {1, 'b', True, 34.22, 44}
print(s1)
print(type(s1))
#Usos interessantes com sets
#Adicionar Elementos em ... |
from adv_prodcon import Producer, Consumer
import time
class MyProducer(Producer):
def __init__(self, *args, **kwargs):
tag = kwargs.pop("tag")
Producer.__init__(self, *args, **kwargs)
self.work_kwargs = {"tag": tag}
@staticmethod
def work(on_start_result, state, message_pipe, *ar... |
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import settings
import glob
import json
import os
from django.db import connection
from django.core.management.commands.runserver import Command as BaseCommand
class Co... |
import os
import multiprocessing
import numpy as np
class ActiveLearningExperiment:
def __init__(self, query_method, instance, gpu_index, dataset_name,
model, train_func, num_init, num_add_per_iter,
num_iter, x_train, y_train, x_test, y_test):
"""
constructor
... |
import itertools
import os
import pytest
import shapely.geometry
from sentinelhub import (
CRS,
BBox,
BBoxSplitter,
CustomGridSplitter,
DataCollection,
OsmSplitter,
TileSplitter,
UtmGridSplitter,
UtmZoneSplitter,
read_data,
)
from sentinelhub.testing_utils import get_input_fold... |
import mne
import numpy as np
'''
https://realpython.com/pypi-publish-python-package/#publishing-to-pypi
https://towardsdatascience.com/how-to-publish-a-python-package-to-pypi-7be9dd5d6dcd
'''
class sim_data:
def __init__ (self):
b = 1
def gen_epochs (self, nchannels=None, labels=None, sfreq=None,
... |
import torch.nn.functional as F
import torch.nn as nn
import torch
import torch.optim as optim
import numpy as np
import math
from torch.nn import init
class NoisyLinear(nn.Module):
"""Factorised Gaussian NoisyNet"""
def __init__(self, in_features, out_features, sigma0=0.5):
super().__init__()
... |
from datetime import datetime, timedelta
import requests
from airflow import DAG
from airflow.operators.python import PythonOperator
from app.utils.terminal import print_to_console
from app.models.dto.user_dto import UserDTO
from app.models.dto.address_dto import AddressDTO
from app.models.dto.company_dto import Comp... |
import hashlib
import inspect
import numpy as np
from .generic import isinstance_str
def hash_path(nodes):
h = hashlib.md5()
for node in nodes:
to_str = []
if isinstance_str(node, 'InputNode'):
to_str.append(node.output)
else:
if isinstance_str(node.layer, 'Lamb... |
import tensorflow as tf
import numpy
import logging
logger = logging.getLogger()
from mlqm import DEFAULT_TENSOR_TYPE
from mlqm.hamiltonians import Hamiltonian
class NuclearPotential(Hamiltonian):
"""Nuclear Physics Potential
"""
def __init__(self, **kwargs):
'''
Arguments:
... |
"""
datalite.constraints module introduces constraint
types that can be used to hint field variables,
that can be used to signal datalite decorator
constraints in the database.
"""
from typing import TypeVar, Union, Tuple
T = TypeVar('T')
class ConstraintFailedError(Exception):
"""
This exception... |
import argparse
from collections import Counter, defaultdict
import json
import random
import re
import time
import numpy as np
from pystalk import BeanstalkClient
from bucket_extraction import getBucketsFromText
import bucket_generation.utils as generation_utils
def generateNGrams(candidates):
ngrams = defau... |
#
# 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... |
entero=5 #Numero entero
lon=5L #Numero LONG
real=0.567 #Numero Real
real=0.56e-3 #Numero Real x 10 a la -3
print real
a = 26
b = 11.3
c = 5
d = 3.5
#SUMA
print a + b
#RESTA
print c - a
#MULTIP
print d * c
#EXPONENTE
print c ** 3
#DIVISION
print c / a
#DIVISION ENTERA
print c / a
#MODULO
print 7%3
|
# Generated by Django 3.2.3 on 2021-08-12 17:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0008_customer_profile_picture'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='pr... |
"""
Functional Test for curve class
"""
import bond_math as bmath
import pandas as pd
# Get expectations
in_curve = pd.read_csv('test_curve_in.csv')
exp_curve_H6 = pd.read_csv('test_curve_H6.csv')
exp_H6 = pd.Series(exp_curve_H6['spot'].tolist(),
index=exp_curve_H6['term'].tolist())
exp_fwd= pd.rea... |
import sys, logging, os, random, math, open_color, arcade
#check to make sure we are running the right version of Python
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
#turn on logging, in case we have to leave ourselves debugging messa... |
import sys
import argparse
import colorama
from rve import cmd
def _create_sub_parsers(parser):
cmds = [cmd.init, cmd.remove, cmd.run, cmd.status]
cmds_names = [x.name for x in cmds]
cmds_list = '[' + '|'.join(cmds_names) + ']'
desc = 'call `rosh command -h` for help in each command listed below:\n... |
from ..typing import Number
from .base import MarkdownSection
__all__ = ["MarkdownCodeBlock"]
class MarkdownCodeBlock(MarkdownSection):
def append(self, line: str) -> None:
self.lines.append(line)
def reformatted(self, width: Number = 88) -> str:
return "\n".join([line.rstrip() for line in ... |
from .robot import Robot
from ..shared import ROBOT, DIRT, BABY, CORRAL, OBSTACLE, get_adjacents, count_dirt
from .utils import closest_target, count_free_babies
from ..logging import LoggerFactory as Logger
log = None
class Reagent(Robot):
'''
Reagent agent. Simple reflex agent
'''
def __init__(sel... |
import unittest
import torch
import torch.nn as nn
from tinynn.prune.oneshot_pruner import OneShotChannelPruner
from interval import Interval
import torch.nn.functional as F
def removed_idx_group_check(removed_idx, total_idx_len, removed_idx_len, group, offset=0):
for i in range(group):
remove_group_len ... |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Pose
def process_odom(msg):
publisher.publish(msg.pose.pose)
rospy.init_node('converter')
publisher = rospy.Publisher('/tractor_position', Pose, queue_size=10)
subscriber = rospy.Subscriber('/gps/rtkfix', Odometry... |
from __future__ import annotations
from identify import cli
def test_identify_cli(capsys):
ret = cli.main(('setup.py',))
out, _ = capsys.readouterr()
assert ret == 0
assert out == '["file", "non-executable", "python", "text"]\n'
def test_identify_cli_filename_only(capsys):
ret = cli.main(('setu... |
# 6.4
glossary = {
'oop': 'object of power',
'loop': 'don\'t like infinite',
'condition': 'every choice is a renunciation',
'tuple': 'change all or nothing',
'immutable': 'like elders, don\'t change anymore',
'dictionaries': 'contain the knowledge',
'indent': 'the way to be clean',
}
for... |
from django.db.models import Q
from django.utils import timezone
from rest_framework import generics
from functools import reduce
from .models import Meeting
from .serializers import MeetingWriteSerializer, MeetingReadSerializer, \
MeetingSerializer
class MeetingListView(generics.ListCreateAPIView):
seriali... |
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket,require_websocket
from collections import defaultdict
from django.http import HttpResponse
# 保存所有接入的用户地址
allconn = defaultdict(list)
@accept_websocket
def echo(request, userid):
allresult = {}
# 获取用户信息
userinfo = request.... |
# https://www.codewars.com/kata/56af1a20509ce5b9b000001e
def travel(r, zipcode):
r_splitted = r.split(',')
house_address = []
house_numbers = []
for address in r_splitted:
if address.count(zipcode) != 0:
address_splitted = address.split()
if zipcode != ' '.jo... |
#!/usr/bin/python3
import hashlib
import threading
import time
import config
#findFlag = 0
#result = 0
myPassword = '12DC4DB5B4636DD86F46C138B2EE0386CC1C5C5FBCF5ED302B3144869D9E500B'
myPassword = myPassword.lower()
#12DC4DB5B4636DD86F46C138B2EE0386CC1C5C5FBCF5ED302B3144869D9E500B
#72D96D46543F3B7A9765... |
from NeuralNet import NeuralNet
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras import backend
class NeuralNetGamma(NeuralNet):
def beginTraining(self):
self.setTrai... |
from CRF import *
|
# IMPORT LIBRARIES
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# IMPORTING DATASET
def rfg(dataset, NOFtrees):
dataset = dataset # pd.read_csv("2_Classification/Social_Network_Ads.csv")
X = dataset.iloc[:, 0:-1].values
y = dataset.iloc[:, -1].values
dataset.plot()
# Spl... |
# -*- coding: utf-8 -*-
""" gtorch_utils/segmentation/loss_functions/test/test_fp_rate """
import torch
import unittest
from gtorch_utils.segmentation.loss_functions.fp_rate import FPR_Loss
from gtorch_utils.segmentation.metrics.fp_rate import fpr
class Test_FPR_Loss(unittest.TestCase):
def setUp(self):
... |
# 분해합
# 브루트포스의 정석
# 각각 1부터 쭉 해주는 것에 for문을 쓰는데 인색하지 말자.
# 정말 앞에서부터 하나하나 쓰는 것을 중심으로 가야한다.
# [boj-백준] Brute force 2231 분해 합 - python
n = int(input())
for i in range(1, n+1):
a = list(map(int, str(i)))
sum_sep = sum(a)
sum_all = i + sum_sep
if sum_all == n:
print(i)
break
if i == n:
... |
import socket
from struct import *
str=input("Enter the Direction : ")
num=int(str)
s = socket.socket()
host = "192.168.43.223"
port = 8001
s.connect((host,port))
print("connection established")
#s.send(val.encode())
val = pack('!i', num)
s.send(val)
|
'''
A + B
Problem Description
Given a series of integer pairs and , output the sum of and .
Input Format
Each line contains two integers, and . One input file may contain several pairs where .
Output Format
Output a single integer per line - The sum of and .
SAMPLE INPUT
1 2
2 5
10 14
SAMPLE OUTPUT
3
7
24
'... |
__all__ = ["check_surr", "gradient", "folder_name_func", "index_list_func", "model_input_func", "model_sig_func", "plot_pred_func", "plot_sig_func", "pred_comp_func", "read", "rename_func", "sig_data_func", "tanh_func", "upper_shelf_func"]
|
from .theplatform import ThePlatformIE
from ..utils import (
ExtractorError,
GeoRestrictedError,
int_or_none,
update_url_query,
urlencode_postdata,
)
class AENetworksBaseIE(ThePlatformIE):
_BASE_URL_REGEX = r'''(?x)https?://
(?:(?:www|play|watch)\.)?
(?P<domain>
(?:... |
from user import User #Importing the user class
from credentials import Credentials #Importing the credentials class
import unittest #Importing python unittest module for testing
class TestPassword(unittest.TestCase):
'''
Test class to test user and credentials classes behaviours.
TestCase class helps in creati... |
'''
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies... |
from django.contrib.auth import get_permission_codename
from django.contrib.contenttypes.models import ContentType
from wagtail.wagtailsnippets.models import get_snippet_models
def get_permission_name(action, model):
return "%s.%s" % (model._meta.app_label, get_permission_codename(action, model._meta))
def use... |
from cm.util import misc
from cm.util import paths
import logging
log = logging.getLogger('cloudman')
class CloudInterface(object):
# Global fields
ec2_conn = None
s3_conn = None
tags_supported = False
tags = {}
# Instance details
ami = None
instance_type = None
instance_id = None... |
# -*- coding: utf-8 -*-
# @Author : Lin Lan (ryan.linlan@gmail.com)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from collections import defaultdict
import ray
import numpy as np
from ray.rllib.optimizers.policy_optimizer import PolicyOp... |
import numpy as np
def test_BEM():
"""Unnecessary test for the ugly and non-working and legacy BEM
for the sake of coverage
"""
from Florence.BoundaryElements import GetBasesBEM2D
from Florence.BoundaryElements import GenerateCoordinates
from Florence.BoundaryElements import CoordsJacobi... |
from conans import CMake, ConanFile, tools
from conans.errors import ConanInvalidConfiguration
import functools
import os
required_conan_version = ">=1.45.0"
class EdynConan(ConanFile):
name = "edyn"
description = "Edyn is a real-time physics engine organized as an ECS"
license = "MIT"
url = "https://... |
print('os numeros pares entre 1 e 50 sao:')
for c in range(0,51,2):
print(c)
print('FIM')
escolha4 = ''
while escolha4 != 'sim' and escolha4 != 'nao':
escolha4 = str(input('você deseja executar novamente [sim/nao]?')).lower()
if escolha4 == 'sim':
import jogo_do_tio_Dodo
if escolha4 == 'nao':
... |
import unittest
import sys
from flow_stress.pt_conditions import *
depth = 10
density = 2.7
geothermal_gradient = 30
class Test_pt_conditions(unittest.TestCase):
def test_pt_conditions_initiates(self):
self.pt = PTCalculator(depth, density, geothermal_gradient)
self.assertEqual(self.pt.gravity, 9.8)
self.as... |
# !/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
from turtle import *
shape("arrow")
speed(2)
up()
goto(-50,0)
down()
bgcolor("dodgerblue")
color("white")
begin_fill()
for i in range(5):
forward(100)
right(144)
end_fill()
hideturtle()
|
from conf import spaces_settings
def spaces_processor(request):
""" Set global template variables. """
return {
'site_name': spaces_settings['SITE_NAME']
}
|
__author__ = 'vitor'
from django.conf import settings
from django.core.mail import send_mail
from collections import defaultdict
import string
def enviar_email(obj):
email_assunto = settings.EMAIL_SUBJECT
habilidades = get_usuario_habilidades(obj)
if habilidades:
for habilidade in h... |
from datetime import datetime, date
from marqeta.response_models import datetime_object
import json
import re
class StoreResponseModel(object):
def __init__(self, json_response):
self.json_response = json_response
def __str__(self):
return json.dumps(self.json_response, default=self.json_seri... |
import taichi as ti
@ti.archs_support_sparse
def test_pointer():
x = ti.field(ti.f32)
s = ti.field(ti.i32)
n = 16
ptr = ti.root.pointer(ti.i, n)
ptr.dense(ti.i, n).place(x)
ti.root.place(s)
s[None] = 0
@ti.kernel
def activate():
ti.activate(ptr, 1)
ti.activate(p... |
from lib.docker import client
from settings.docker import HOSTNAME
def all(driver='bridge'):
return client.networks.list(filters={'driver': driver})
def get(network_id):
return client.networks.get(network_id)
def get_containers_from(network_id):
network = get(network_id)
if network:
return... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
# Built-in modules #
import os, sh, glob, shutil, stat
# Internal modules #
from seqenv.common import unzip
from seqenv.common.cache import property_cached
################################################################################
class DirectoryPath(str):
def __repr__(self): return '<%s object "%s">' % (s... |
from num2words import num2words
import Python_Education_Base.GeekBrains_Python_Base_Work_With_Files_Practice.generators as Generarators
import re
filename = 'ex4.txt'
Generarators.ex4_gen(filename, 1000)
with open(filename, 'r') as f:
pattern = re.compile(r"(.+)-(\d+)", re.UNICODE)
for line in f.readlines():
... |
from __future__ import print_function
import json
import boto3
import traceback
ddb = boto3.client('dynamodb', region_name = 'cn-northwest-1')
#print('Loading function')
event_delete = {
"Records": [
{
"eventID": "9bc813d4c24bcc307147ac25a170b44d",
"eventVersion": "1.1",
"dynamodb": {
"Keys": {
"recordId": {
"N": "... |
import re
from urllib.request import urlretrieve
dev_settings_path = "hifireg/hifireg/settings/developer.py"
def wget(url, dest_path):
urlretrieve(url, dest_path)
def get_current_database_postfix():
try:
with open(dev_settings_path, "r") as f:
for line in f:
match_list = r... |
import requests
import flask
import yfinance as yf
from pandas_datareader import data as pdr
import dash_table
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
from datetime import datetime as d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import csv
import logging
import gzip
from bs4 import BeautifulSoup
from scraper import SimpleScraper, SeleniumScraper
from random import randint
import requests
IA_WEB_BASE_URL = 'http://web.archive.org'
def setup_logger():
""" Set up log... |
from graphene_django.types import DjangoObjectType
from kollect.models import Like
class LikeNode(DjangoObjectType):
class Meta:
model = Like
name = "Like"
|
""" Countries and cities models """
from django.db import models
class Country(models.Model):
name = models.CharField("Country name", max_length=50)
def __str__(self):
return self.name
class City(models.Model):
name = models.CharField("City name", max_length=50)
country_id = models.ForeignKe... |
from test import *
from MR import *
t=Test()
def test_nbit_odd(data):
out=nbit_odd(*data)
if out%2==0:
return False
n=data[0]
for i in range(n-1):
out//=2
if out>2:
return False
out//=2
if out!=0:
return False
return True
t.regist(nbit_odd)
t.regist... |
import re
import unicodedata
from .base import Service, Tokenizer, triples
def maketrans_remove(accents=("COMBINING ACUTE ACCENT", "COMBINING GRAVE ACCENT")):
""" Makes a translation for removing accents from a string. """
return str.maketrans("", "", "".join([unicodedata.lookup(a) for a in accents]))
clas... |
from .core import search_rental, search_reserve # noqa F401
|
from app.notify_client.inbound_number_client import InboundNumberClient
def test_add_inbound_sms_number(mocker, api_user_active):
inbound_number = '12345678901'
expected_url = '/inbound-number/add'
client = InboundNumberClient()
mock_post = mocker.patch('app.notify_client.inbound_number_client.Inboun... |
"""samples 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')
Class-based... |
import matplotlib.pyplot as plt
import math
# this is a helper script to properly choose the epsilon rate of decay during DQN training
start = 1.0
end = 0.1
decay = 14000
steps = 80000
thresholds = []
for i in range(steps):
threshold = end + (start - end) * \
math.exp(-1 * i / decay)
thresholds.appe... |
# Looks like it relies on precisions from C
# Running it as C (https://www.codechef.com/ide) gives:
c_output = '0001010203040406090c0d12282d2e3034'
# Running it as superhack (http://www.hacker.org/sh/) gives:
superhack_output = '102'
|
# Copyright MaxAndMitchCorp 2020
from trust_simulator import TrustSimulator
from society import Society
from institution import Institution
import pytest
@pytest.mark.parametrize("alpha", [(1), (0.05)])
def test_societal_convergence(alpha):
society = Society(population_size=100, connectivity_probability=0.1)
... |
# ニュートン法の収束地図の原点拡大アニメーションを作成するコード
from PIL import Image, ImageDraw
from numba import jit
@jit
def newton(x):
for _ in range(50):
x = x - (x**3-1)/(3*x**2)
return x
@jit
def plot(draw, s, mag):
hs = s/2
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
for x in range(s):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
from typing import (Callable, Iterable, Iterator, List, Sequence, Tuple,
TypeVar, Union)
SHOW_FUNC_DATA = Sequence[Path]
SHOW_FUNC = Callable[[bool, SHOW_FUNC_DATA], None]
DIFF_FUNC = Callable[
[Sequence[str], Sequence[st... |
from MonkeyBook.extensions import db
from sqlalchemy_utils import EmailType
from sqlalchemy import ForeignKeyConstraint
monkey_friends = db.Table('monkey_friends',
db.Column(
'monkey_id', db.Integer,
db.ForeignKey('monkey.id', onupdate='CASCADE', ondelete='CASCADE'),
primary_key=True
... |
#!/usr/bin/python
#rev 2015-11-12
print "Importing python modules ..."
from time import time
start_time = time()
from numpy import loadtxt
print("--- numpy %s seconds ---" % (time() - start_time))
import matplotlib.pyplot as plt
print("--- matplotlib %s seconds ---" % (time() - start_time))
from itertools import cyc... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
from rply import ParserGenerator
from rply.token import Token
from .ast import *
from .errors import *
class ParserState:
def __init__(self):
pass
def add_variable(self, var):
self.variables.append(var)
def add_constant(self, var):
self.constants.append(var)
class Parser:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 19 01:52:59 2022
@author: maout
"""
from typing import Union
import numpy as np
import torch
__all__ = ['RBF']
class RBF:
"""
RBF kernel class for pytorch implementation.
"""
def __init__(self, length_scale: Union[float,... |
from more_itertools import one
import pytest
from adam.learner.integrated_learner import IntegratedTemplateLearner
from adam.learner.language_mode import LanguageMode
from adam.ontology.phase1_ontology import DAD, GAILA_PHASE_1_ONTOLOGY
from adam.perception import PerceptualRepresentation
from adam.perception.high_leve... |
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
import math
def fractal(pt1,pt2,angle):
# creating a curve to extract its division points
line=rs.AddLine(pt1,pt2)
points=rs.DivideCurve(line,4)
# 1/3 point
between_points_1=points[1]
between_points_2=points[3]
# mid vector... |
# Copyright 2019 The PlaNet Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
import pytest
from typing import Optional
from pygraphy.types import (
Object,
Input,
Schema,
field
)
from examples.starwars.schema import Schema as StarwarsSchema
from examples.simple_example import Schema as SimpleSchema
from examples.complex_example import Schema as ComplexSchema
pytestmark = pytes... |
#!/usr/bin/python
DOCUMENTATION = '''
---
module: bmf_rest_bigchain_create_chain
short_description: BMF BigChain create chain
description:
- Makes HTTPS request to create chain.
version_added: "1.0.0"
author:
- Ted Elhourani (ted@bigswitch.com)
notes:
- This module can only be called in a playbook with the conn... |
from discord.ext import commands
import discord
import json
import logging
from .utils import data
discord_logger = logging.getLogger('discord')
class Administrator(commands.Cog):
@commands.command(brief="Reloads a module.")
@commands.check(commands.is_owner())
async def reload(self, ctx: commands.Context,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.