content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
'''
Shapeless bot for MsgRoom @ Windows96.net
Shapeless bot © Diicorp95. MIT License
Windows 96 © Mikesoft. All rights reserved, except for some parts
Open-Source Part: Functional Wrap for File System (excerpt)
'''
import os.path # not implemented
def askterm(s,mgrp):
s+=' (y/n): '
i... | python |
"""Graph database for storing harvested data."""
from neo4j import GraphDatabase
from neo4j.exceptions import ServiceUnavailable, ConstraintError
from typing import Tuple, Dict, Set
import logging
import json
from pathlib import Path
from os import environ
import boto3
import base64
from botocore.exceptions import Clie... | python |
import os
from glue.core import data_factories as df
from glue.tests.helpers import requires_astropy
DATA = os.path.join(os.path.dirname(__file__), 'data')
@requires_astropy
def test_load_vot():
# This checks that we can load a VO table which incidentally is a subset of
# the one included in the tutorial.
... | python |
#Faça um programa que leia um ano e mostre se ele é BISSEXTO
a = int(input('Digite um ano: '))
if a % 4 == 0:
print(f'O ano {a} é BISSEXTO')
else:
print(f'O ano {a} NÃO É BISSEXTO')
| python |
with open("myside.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "<Media omitted>" not in line:
f.write(line)
f.truncate()
with open("otherside.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "<Media omitted>" not in... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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... | python |
import unittest
from rx.core import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
... | python |
"""
The transport decorator (~transport).
This decorator allows changes to agent response behaviour and queue status updates.
"""
from marshmallow import fields, validate
from ..models.base import BaseModel, BaseModelSchema
from ..valid import UUIDFour, WHOLE_NUM
class TransportDecorator(BaseModel):
"""Class r... | python |
for svc in SERVICES:
db.define_table(
'report_card_%s' % svc[0],
Field('choose_file', 'upload', uploadfield='file_data'),
Field('file_data', 'blob'),
Field('file_description', requires=IS_NOT_EMPTY()),
)
db.define_table(
'award',
YES_NO_FIELD,
)
db.de... | python |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | python |
# Generated by Django 3.2.8 on 2022-02-02 20:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ProjectSite', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... | python |
#-------------------------------------------------------------------------------------------
'''
#barchar and histogram of sensors
df = pd.read_csv('../data/trafico/raw_data/07-2020.csv', sep=';')
df_month = df.groupby(['id']).mean()
fig = px.bar(x = df_month.index, y=df_month['intensidad'])
fig.show()
fig = px.hist... | python |
#assignment one
k=float(input("\t\tENTER THE VALUE OF K = \t"))
p=(k-1)/(k+1)
print(p)
#the value of p is
#assignment two
x=int(input("\t\tENTER THE VALUE OF X = \t"))
y=int(input("\t\tENTER THE VALUE OF Y = \t"))
z=int(input("\t\tENTER THE VALUE OF Z = \t"))
result=max(min(x,y),z)
#the value stored in... | python |
import numpy as np
class MaskGenerator(object):
def __init__(self, h, w, rng=None):
self.h = h
self.w = w
if rng is None:
rng = np.random.RandomState(None)
self.rng = rng
def gen(self, n):
return np.ones((n, h, w))
class AllOnesMaskGenerator(MaskGenerator)... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-09-13 05:13
import core.csv_export
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracon2018', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Pois... | python |
import cProfile
def test_fib(func):
lst = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i, item in enumerate(lst):
assert item == func(i)
print(f'Test {i} OK')
def fib_list(n):
fib_l = [None] * 1000
fib_l[:2] = [0, 1]
def _fib_list(n):
if fib_l[n] is None:
fib_l[n] =... | python |
import logging
from boto3 import client
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
class SSM:
"""An SSM class that provides a generic boto3 SSM client with specific SSM
functionality necessary for dspace submission service"""
def __init__(self):
self.client... | python |
# https://github.com/georgezlei/algorithm-training-py
# Author: George Lei
import random
def union_find(vertices, edges):
unions = [i for i in range(vertices)]
for a, b in edges:
while a != unions[a]:
a = unions[a]
while b != unions[b]:
b = unions[b]
unions[b] = a
return len([i for i i... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import render
from models import *
# Create your views here.
def home(request):
texto = "banana"
template =... | python |
import json
import plotly
import pandas as pd
import joblib
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar... | python |
import gzip
import os
from parser import Parser
path = os.getcwd() + "/corpus"
articles = ["a", "the", "an"]
pronouns = ["i", "you", "we", "it", "they", "he", "she", "my", "mine", "their", "theirs", "his",
"her", "that", "this", "us", "me", "him"]
connectives = ["in", "s", "d", "t", "by", "of",... | python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _HLRBRep... | python |
# -*- coding: utf-8 -*-
"""
continuity.tests.github
~~~~~~~~~~~~~~~~~~~~~~~
Continuity GitHub tests.
:copyright: 2015 by Jonathan Zempel.
:license: BSD, see LICENSE for more details.
"""
from . import ContinuityTestCase
class GitHubCommandTestCase(ContinuityTestCase):
"""Base GitHub command... | python |
class A:
def f2(self, *args, a = 1):
pass
class B(A):
def f2(self, *args, a=1):
<selection>super().f2(*args, a=a)</selection>
| python |
# Generated from 'Movies.h'
def FOUR_CHAR_CODE(x): return x
xmlIdentifierUnrecognized = -1
kControllerMinimum = -0xf777
notImplementedMusicOSErr = -2071
cantSendToSynthesizerOSErr = -2072
cantReceiveFromSynthesizerOSErr = -2073
illegalVoiceAllocationOSErr = -2074
illegalPartOSErr = -2075
illegal... | python |
from part2 import test_num
def test_test_num():
assert test_num(112233) == True, "Expected 112233 to pass"
assert test_num(123444) == False, "Expected 123444 to fail"
assert test_num(111133) == True, "Expected 111133 to pass"
print("Passed!")
if __name__ == "__main__":
test_test_num()
| python |
# -*- coding: utf-8
from richtypo import Richtypo
from richtypo.rules import NBSP
def test_russian_simple():
r = Richtypo(ruleset='ru-lite')
text = u'Из-под топота копыт'
assert r.richtypo(text) == u'Из-под%sтопота копыт' % NBSP
def test_unicode_with_ascii_only_characters():
"""
If this test doe... | python |
#!/usr/bin/env python2.7
import csv
import sys
import re
from printf import printf
a = [1,2,4,5,6,9,10,13,17,19,20,36,38,39,52,68]
try:
if (sys.argv[1] == '-'):
f = sys.stdin.read().splitlines()
else:
filename = sys.argv[1]
f = open(filename, 'r')
csv = csv.reader(f)
data = list(csv)
for row i... | python |
__author__ = 'Aneil Mallavarapu (http://github.com/aneilbaboo)'
from datetime import datetime
import dateutil.parser
from errors import InvalidTypeException
def default_timestamp_parser(s):
try:
if dateutil.parser.parse(s):
return True
else:
return False
except:
... | python |
#!env python3
# Time-Stamp: <2021-04-20 19:12:36>
# Copyright 2021 Sho Iwamoto / Misho
#
# 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
# Unle... | python |
"""
Download data from here: https://drive.switch.ch/index.php/s/vmAZzryGI8U8rcE
Or full dataset here: https://github.com/Waller-Lab/LenslessLearning
```
python scripts/evaluate_mirflickr_admm.py \
--data DiffuserCam_Mirflickr_200_3011302021_11h43_seed11 \
--n_files 10 --save
```
"""
import glob
import os
import pa... | python |
import argparse
import logging
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import torch
from typeguard import check_argument_types
from typeguard import check_return_type
from espnet2.... | python |
#!/usr/bin/env python
import pcd8544.lcd as lcd
logo = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # 0x0010 (16) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xF8, 0xFC, 0xAE, 0x0E, 0x0E, 0x06, 0x0E, 0x06, # 0x0020 (32) pixels
0xCE, 0x86, 0x8E, 0x0E,... | python |
import os
import errno
from ftplib import FTP
# this is used to get all tickers from the market.
exportList = []
class NasdaqController:
def getList(self):
return exportList
def __init__(self, update=True):
self.filenames = {
"otherlisted": "data/otherlisted.txt",
"na... | python |
import hashlib
import json
from pathlib import Path
from typing import TYPE_CHECKING
from poetry.core.packages.utils.link import Link
from .chooser import InvalidWheelName
from .chooser import Wheel
if TYPE_CHECKING:
from typing import List
from typing import Optional
from poetry.config.config import ... | python |
import os
import json
from json import JSONDecodeError
from .base import PersistentData
def get_key_files(alternate_key_dir=None):
key_dir = alternate_key_dir or PersistentData.config_dir
try:
keyfile_walk = next(os.walk(key_dir))
root, dirs, keyfiles = keyfile_walk
key_file_list = [o... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_schemas.base import BaseMultiSchema
from polyaxon_schemas.ml.layers.advanced_activations import (
ELUConfig,
LeakyReLUConfig,
PReLUConfig,
ThresholdedReLUConfig
)
from polyaxon_schemas.ml.layers.convo... | python |
# Importação das Livrarias
import numpy as np
import matplotlib.pyplot as plt
# TODO:
# Passo 0: Inicializar o vector de peso e o enviesamento com zeros (ou pequenos valores aleatórios).
# Passo 1: Calcular uma combinação linear das características e pesos de entrada.
# Passo 2: Aplicar a função sigmoide, que retorna ... | python |
#
# DecoTengu - dive decompression library.
#
# Copyright (C) 2013-2018 by Artur Wroblewski <wrobell@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License... | python |
from typing import Callable, Union
from pandas import DataFrame
from ..utils import load as load__
from .paths import file_paths as paths__
def load(
keys,
info: Union[bool, Callable] = False,
) -> Union[DataFrame, dict]:
if isinstance(keys, list):
paths = {
key: paths__[key]
... | python |
import os.path
import numpy as np
import keras.models
from keras.models import model_from_json
import tensorflow as tf
my_path = os.path.abspath(os.path.dirname(__file__))
digit_model_json = os.path.join(my_path, "../../static/models/digit_model.json")
digit_model_h5 = os.path.join(my_path, "../../static/models/digit... | python |
#ucapan selamat tahun baru
ucapan_happynewyear = ['hello world', 'selamat tahun baru', 'stay safe be productive', 'happy new year', 'Shinen akemashite omedetou gozaimasu 新年あけましておめでとうございます', 'keep spirit and enjoy life']
Mywish_newyear2022 = ['keep productive', 'improving grade', 'accept on state university']
#prin... | python |
#Licensed under Apache 2.0 License.
#© 2020 Battelle Energy Alliance, LLC
#ALL RIGHTS RESERVED
#.
#Prepared by Battelle Energy Alliance, LLC
#Under Contract No. DE-AC07-05ID14517
#With the U. S. Department of Energy
#.
#NOTICE: This computer software was prepared by Battelle Energy
#Alliance, LLC, hereinafter the Cont... | python |
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Function
from torch.autograd import Variable
from utils.box_utils import decode
# test_RFB.py中被调用,生成的detector对象,结合net输出的out(forward中拆分为loc + conf,结合RFBNet结构,
# 可以发现是一个全卷积的feature map,可以结合multibox函数理解),conf就是预测的分类得分,
# lo... | python |
import textwrap
import datetime
import glob
from collections import Counter
from .getApi import getApi
from .Exceptions import NoTownError
def funcShelves(townName):
# API取得部
town = getApi("town", "https://so2-api.mutoys.com/master/area.json")
sale = getApi("sale", "https://so2-api.mutoys.com/json/sale/al... | python |
from __future__ import absolute_import
from datetime import datetime
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import helpers
from django.contrib.admin.util import (display_for_field, label_for_field,
lookup_field, NestedObjects)
from django.contrib.admin.views.ma... | python |
# %%
import cv2
import os
import argparse
import time
import func
import numpy as np
# %% args
parser = argparse.ArgumentParser()
parser.add_argument('-I','--image',
default='100',
help='import image type, such as 100 or Die')
# 輸入圖片類型,範例為'100'及'Die'
parser.add_... | python |
from redis import Sentinel, Redis
from app.core.config import settings
import app.core.logging
sentinel = Sentinel([(settings.REDIS_SENTINEL_SERVER, settings.REDIS_SENTINEL_PORT)], socket_timeout=0.1)
masters = sentinel.discover_master('mymaster')
slaves = sentinel.discover_slaves('mymaster')
master = sentinel.mas... | python |
import os
import csv
from dream_funcs import DeepDream
from PIL import Image, ImageChops
import numpy as np
# deepdream setup
blend_frames = True
alpha_step = 0.5
layer = 'mixed5b_1x1'
channel = 314
n_iter = 30
step = 1.5
octaves = 8
octave_scale = 1.5
dd = DeepDream(layer, (lambda T: T[:,:,:,channel]))
# file data... | python |
# -*- coding: utf-8 -*-
"""
Defines earth model objects.
:copyright: 2017 Agile Geoscience
:license: Apache 2.0
"""
import re
import os
import copy
import numpy as np
from bs4 import BeautifulSoup
import vtk
from vtk.util.numpy_support import vtk_to_numpy
import matplotlib.pyplot as plt
from bruges.transform import d... | python |
#!/usr/bin/python
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/image')
def get_image():
filename = 'sid.png'
return send_file(filename, mimetype='image/png')
| python |
from .graph_export import export_scenegraph, export_subtree
from .graph_import import import_scenegraph, import_subtree
| python |
import requests
import json
from datetime import datetime,timedelta
class T(object):
ENDPOINT = "http://realtime.mbta.com/developer/api/v2/{apicall}"
def __init__(self, api_key, response_format='json'):
if api_key == "YOUR API KEY HERE" or api_key.strip() == "":
raise ValueError("Fill in a... | python |
"""templates
"""
from flask import render_template, request, flash, url_for, redirect, \
send_from_directory, session
from flask_login import current_user
import datajoint as dj
from ast import literal_eval
from loris import config
from loris.app.forms.dynamic_form import DynamicForm
from loris.app.utils import u... | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | python |
# -*- coding: utf-8 -*-
"""
存储器,支持redis存储,使用zset对代理去重加评分,提供flask的api接口
"""
import random
import re
import redis
from proxypool.error import PoolEmptyError
from proxypool.settings import HOST,PORT,PASSWORD,DB,INITIAL_SCORE,REDIS_KEY,MIN_SCORE,MAX_SCORE
class RedisClient(object):
def __init__(self):
if PA... | python |
# -*- coding: utf-8 -*-
'''
julabo.py
Contains Julabo temperature control
see documentation http://www.julabo.com/sites/default/files/downloads/manuals/french/19524837-V2.pdf at section 10.2.
:copyright: (c) 2015 by Maxime DAUPHIN
:license: MIT, see LICENSE for details
'''
import serial
import time
from .pytempera... | python |
import os
import sys
from pathlib import Path
import numpy as np
# Utils
filepath = Path(__file__).resolve().parent
# sys.path.append( os.path.abspath(filepath/'../ml') )
from ml.keras_utils import r2_krs
from ml.data import extract_subset_fea
try:
import tensorflow as tf
if int(tf.__version__.split('.')[0])... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Future Internet Consulting and Development Solutions S.L.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License,... | python |
import time
from nesta.server.define import define
def test_server(control):
# send stop command and check status
resp = control.execute(command="server", argv=["stop"])
assert resp.exitcode == 0
time.sleep(0.5)
resp = control.execute(command="server", argv=["status"])
assert resp.exitcode =... | python |
#!/usr/bin/env python
import copy
def split_train_override_patch(patch, train_parameter_list:list):
"""
This function returns a list of tuples containing only those parameters that are in the train_parameter_list,
and a second list of tuples with the overridden parameters
:param patch: original patch ... | python |
from ._UFDLObjectDetectionRouter import UFDLObjectDetectionRouter
| python |
import cv2
img = cv2.imread("./images/sample_01.jpg", cv2.IMREAD_COLOR)
cv2.imshow("My image", img)
cv2.waitKey(0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("My image", gray)
cv2.waitKey(0)
cascade = cv2.CascadeClassifier(cv2.haarcascades + "haarcascade_frontalcatface.xml")
faces = cascade.detectMult... | python |
"""rest_url has to be hidden. Move it from ui_metadata
to the lux_layer_internal_wms
Revision ID: 46cb4ef6fd45
Revises: 1b9b2d6fb6e
Create Date: 2015-01-07 11:32:20.615816
"""
# revision identifiers, used by Alembic.
revision = '46cb4ef6fd45'
down_revision = '1b9b2d6fb6e'
branch_labels = None
depends_on = None
from... | python |
import logging
import os
from handler.handler_context import HandlerContext
from handler.model.base import FieldMask, HandlerBase, merge_resource
from handler.model.model_reply import ModelReply
from handler.model.model_thread import ModelThread
from handler.model.model_user import ModelUser
from handler.model.user im... | python |
''' Criação de um cronometro feito com POO'''
from tkinter import *
from tokenize import String
class Stopwatch(Frame):
def __init__(self, window = None):
# Instancias da classe
super().__init__(window)
self.window = window
self.running = False # Utilizado para con... | python |
import numpy as np # linear algebra
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, losses
from tensorflow.keras.datase... | python |
from PythonPLC import plc
import snap7.client as c
from snap7.util import *
from snap7.snap7types import *
# Custom functions
def ReadOutput(plc,byte,bit,datatype = S7WLBit):
result = plc.read_area(areas['PA'],0,byte,datatype)
if datatype==S7WLBit:
return get_bool(result,0,bit)
elif datatype==S7WLB... | python |
##############################################
# MusicAnalyzer | 15-112 Term Project
# Joel Anyanti | Janyanti
##############################################
##############################################
# Imports
##############################################
from GameObjects import MusicNote
from Settings import ... | python |
import os
import re
import StringIO
class Viewer(object):
def __init__(self):
'''
'''
self.__query_viewer_regex = re.compile('^/deep/.*$')
self.__web_dir = 'web/'
def content_type(self, extension):
'''
'''
return {
'.js': 'text/javascript',
'.html': 'text/html',
'.p... | python |
#!/usr/bin/env python3
# Pedir al usuario dos números válidos, si no son válidos seguir pidiendo valores.
Efectuar con ellos la suma, resta, multiplicación, división, división entera, resto, y potencias.
Utilice control de errores para evitar el error de división entre cero.
| python |
"""
@author: Rossi
@time: 2021-01-26
"""
from collections import OrderedDict, defaultdict
import re
from Broca.message import BotMessage
from .event import ExternalEnd, ExternalStart, SkillStarted, SkillEnded
from .event import BotUttered, SlotSetted, Form, Undo
class Skill:
def __init__(self):
self.nam... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import hydra
import combustion
config_path = "../conf"
config_name = "config"
log = logging.getLogger(__name__)
if "WORLD_SIZE" not in os.environ:
combustion.initialize(config_path=config_path, config_name=config_name)
print("Called in... | python |
__all__ = [
"Currencies",
"CurrencyResource",
]
from decimal import Decimal
from typing import Optional
from pydantic import validator
from decaf.api.client.machinery import BaseResource, ResourceListEndpoint, ResourceRetrieveEndpoint, command
from decaf.api.client.types import Currency, Date
class Currenc... | python |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
from unittest import TestCase
from pyiron_feal.utils import JobName, bfs
import numpy as np
class TestJobName(TestCase... | python |
"""
=======================
Coarse Motor Processes
=======================
"""
import os
import random
import math
import numpy as np
from numpy import linspace
# vivarium-core imports
from vivarium.core.process import Process
# plots
from chemotaxis.plots.coarse_motor import plot_variable_receptor
# directories
f... | python |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import recipe_api
DEPS = [
'commit_position',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/raw_io',
... | python |
import math
import matplotlib.pyplot as pl
import numpy as np
def euler1(F, a, b, x0, y0, n):
Ly = [y0]
Lx = [x0]
x= x0
y= y0
h=(b-a)/n
while x <= b:
y= h*F(x,y)+y
x+=h
Lx.append(x)
Ly.append(y)
x= x0
y= y0
while x >= a:
y=... | python |
import autograd.numpy as anp
from pymoo.model.problem import Problem
from pymoo.problems.util import load_pareto_front_from_file
class CTP(Problem):
def __init__(self, n_var=2, n_constr=1, option="linear"):
super().__init__(n_var=n_var, n_obj=2, n_constr=n_constr, xl=0, xu=1, type_var=anp.double)
... | python |
def bumps(road: str) -> str:
return "Woohoo!" if road.count('n') <= 15 else "Car Dead"
| python |
# Generated by Django 2.1.5 on 2019-01-25 09:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0004_auto_20190125_1230'),
]
operations = [
migrations.RenameField(
model_name='choice',
old_name='feature1',
... | python |
"""All output classes.
AffineDynamicOutput - Base class for outputs with dynamics that decompose affinely in the input.
FeedbackLinearizableOutput - Base class for feedback linearizable outputs.
Output - Base class for outputs
PDOutput - Base class for outputs with proportional and derivative components.
RoboticSystem... | python |
# coding: utf-8
# DO NOT EDIT
# Autogenerated from the notebook kernel_density.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
# # 核密度估计
#
# 核密度估计是使用 *核函数* $K(u)$ 估计一个未知概率密度函数的过程。 直方图可以对任意区域中数据点的数量进行计数,
# 而核密度估计是定义每个数据点的核函数之和的函数。 核函数通常具有以下属性:
#
# 1. 对称,使得 $K(u) = K(-... | python |
import logging
from functools import wraps
from .rpc import RPC
logger = logging.getLogger(__package__)
class NFSv4(RPC):
pass | python |
import gym
import gym_maze
from agent.q_learning import QLearning
env = gym.make("maze-sample-10x10-v0")
env = gym.wrappers.Monitor(env, "q_learning", force=True)
agent = QLearning(env, discount_factor=0.9)
episodes = 10000
horizon = 10000
epsilon = 0.8
alpha = 1
for episode in range(episodes):
observation = env.... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*
from warnings import simplefilter
# ignore all future warnings
simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
import argparse
import os
import pdb
__author__ = "Rickard Hammarén @hammarn... | python |
# Generated by Django 2.0.6 on 2018-07-13 06:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('parkingsystem', '0021_ticket_amount'),
]
operations = [
migrations.RemoveField(
model_name='ticket',
name='amount',
... | python |
from selenium.webdriver.support.select import Select
from common.webdriver_factory import get_driver
driver = get_driver('chrome')
driver.get('https://formsmarts.com/form/axi?mode=h5')
first_name = driver.find_element_by_id('u_LY9_60857')
first_name.clear()
first_name.send_keys('Angie')
last_name = driver.find_elemen... | python |
from crosswalk_client import Client
import pytest
def test_setup(token, service):
client = Client(token, service)
client.create_domain("presidents")
client.create_domain("politicians")
client.bulk_create([{"name": "George W. Bush"}], domain="politicians")
client.bulk_create([{"name": "George W. Bu... | python |
# -*- coding: utf-8 -*-
from .server import RaspiIOServer, get_registered_handles
if __name__ == "__main__":
server = RaspiIOServer()
for handle in get_registered_handles():
server.register(handle)
server.run_forever()
| python |
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.auth.backends import BaseBackend
from django.db.models import Exists, OuterRef, Q
from django.core.exceptions import ValidationError
from rbac_auth.utils import validate_email
UserModel = get_user_mode... | python |
#!/usr/bin/env python
import random
import re
import time
import datetime
import sqlite3
import os
import itertools
import requests
import eveapi
from bs4 import BeautifulSoup
conn = sqlite3.connect(os.path.expanduser("~/eve.sqlite"))
HOME = "PR-8CA"
def calc_jumps(system, start):
url = "http://evemaps.dotlan.net/ro... | python |
#
# Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
# Use of this file is governed by the BSD 3-clause license that
# can be found in the LICENSE.txt file in the project root.
from antlr4.atn.ATNState import StarLoopEntryState
from antlr4.atn.ATNConfigSet import ATNConfigSet
from antlr4.dfa.DFAState im... | python |
import numpy as np
"""
this file will create a GM(grey prediction machine), and enable user to predict the future data based on current array of data. please note that this
machine is based on first order differential equation, so it will be good at predicting data with certain trend( growing or minimizing), not very ... | python |
"""
Test the gva logger, this extends the Python logging logger.
We test that the trace method and decorators raise no errors.
"""
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from gva.logging import LEVELS, get_logger, error_trap, verbose_logger
try:
from rich import traceback
... | python |
import logging, json, requests, jieba, sys, os, copy, re
#from nlutools import tools as nlu
from english_corrector import EnglishCorrector
from data_utils import load_word_freq_dict, _get_custom_confusion_dict
from utils import re_en, re_salary, is_alphabet_string, pinyin2hanzi, ErrorType, PUNCTUATION_LIST
from config ... | python |
from .redict import ReDict, update_with_redict
| python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
df = pd.DataFrame(np.random.choice(np.arange(0, 2), p=[0.9, 0.1],size=(10000, 5)), columns=list('ABCDE'))
total_views = 10000
num_ads = 5
ad_list = []
total_reward = 0
for view in range(total_views):
ad = random.randrange(num_ad... | python |
"""
Optimizers
---------
Module description
"""
from abc import ABC, abstractmethod
from collections.abc import Iterable
import copy
import torch
from brancher.standard_variables import Link
from brancher.modules import ParameterModule, EmptyModule
from brancher.variables import BrancherClass, Variable, Probabilistic... | python |
from PyQt5.QtWidgets import (QWidget, QToolButton, QPushButton, QVBoxLayout,
QHBoxLayout, QWidgetAction, QMenu)
from PyQt5.QtCore import Qt, pyqtSignal, QModelIndex, QSize
from transcode.pyqtgui.qitemmodel import (QItemModel, Node, ChildNodes,
NoCh... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.