content stringlengths 5 1.05M |
|---|
import numpy as np
def correct_to_01(X, epsilon=1.0e-10):
X[np.logical_and(X < 0, X >= 0 - epsilon)] = 0
X[np.logical_and(X > 1, X <= 1 + epsilon)] = 1
return X
def _shape_mixed(x, A=5.0, alpha=1.0):
aux = 2.0 * A * np.pi
ret = np.power(1.0 - x - (np.cos(aux * x + 0.5 * np.pi) / aux), alpha)
r... |
import numpy as np
import torch
from mlprogram.actions import (
ActionSequence,
ApplyRule,
CloseVariadicFieldRule,
ExpandTreeRule,
GenerateToken,
NodeConstraint,
NodeType,
)
from mlprogram.encoders import ActionSequenceEncoder, Samples
from mlprogram.languages import Token
class TestEncod... |
import sys
depth = int(input("What is the well's depth? "))
jump = int(input("Enter the height the frog can jump up: "))
slip = int(input("Enter the height the frog slips down: "))
step = depth
day = 1
if jump-slip<=0 and jump<depth:
print("The frog will never escape from the well.")
sys.exit()
while step>0:
... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyIncremental(PythonPackage):
"""A small library that versions your Python projects."""
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 08:50:32 2019
@author: Thiago
"""
import numpy as np
import pylab as pl
#%%
#
# Modelo paramétrico
#
def profit_(P, L, R, C, H):
return L*R*P - (H+L*C)
#%%
#
# Geração de entradas aleatorias
#
#numero de iterações
N = 10**5
P = np.random.uniform(47, 53, s... |
import torch.nn as nn
import torch.nn.functional as func
class Flatten(nn.Module):
def forward(self, x):
"""Flatten non-batch dimensions."""
return x.view(x.shape[0], -1)
class FullyConnected(nn.Module):
def __init__(self, num_features, hidden_size, dropout):
super(FullyConnected, sel... |
from swarm import Swarm
from status_types import Status
|
# -*- coding: UTF-8 -*-
from django.db import connection
from django.utils.deprecation import MiddlewareMixin
class AuditMiddleware(MiddlewareMixin):
"""
Has to be placed after Django AuthMiddleware.
"""
def process_request(self, request):
cursor = connection.cursor()
# alternative h... |
""" Test chemistry attributes
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2017-05-10
:Copyright: 2017, Karr Lab
:License: MIT
"""
from obj_tables import core
from wc_utils.util import chem
import bcforms
import bpforms
import lark.exceptions
import obj_tables.chem
import openbabel
import unittest
class ChemicalFo... |
from typing import ClassVar, List, Optional
from ...constants import ApiKey, ResourceType
from ..base import RequestData
class Config:
name: str
config_operation: int
value: Optional[str]
def __init__(self, name: str, config_operation: int, value: Optional[str]):
"""
:param name: Th... |
import random
import datetime
import time
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.ensemble import RandomForestRegressor, BaggingRegressor, RandomForestClassifier
from sklearn.svm import SVC,SVR,LinearSVC
from sklearn.naive_bayes imp... |
import string
import random
class User:
"""
Class that generates new instances of users
"""
user_log = [] # Empty user log
def __init__(self, user_name, user_password):
'''
__init__ method that helps us define properties for our objects.
Args:
user_name: New ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# 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... |
from django.urls import path, include
from .views import UserViewSet , customUserRegister ,custom_user_login
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
router = routers.DefaultRouter()
router.register('users', UserViewSet)
urlpatterns = [
p... |
import heapq
h = []
heapq.heappush(h, (10.1, 0))
heapq.heappush(h, (1.1, 1))
print(h)
assert h == [(1.1, 1), (10.1, 0)]
|
# Copyright 2018 AimBrain Ltd.
# 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 agree... |
Code:
print(input().replace('1', 'one')) |
lr = 0.0006
optimizer = dict(
name='torch_optimizer',
torch_optim_class='Adam',
lr=lr,
parameters=[
dict(
params='conv_offset',
lr=lr * 0.1 # 1/10 lr for DCNv2 offsets
),
dict(
params='__others__'
)
]
)
|
# Copyright (c) 2020-2022 Adam Karpierz
# Licensed under the zlib/libpng License
# https://opensource.org/licenses/Zlib
from .__about__ import * ; del __about__ # noqa
from ._about import * ; del _about # noqa
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/swaps.ipynb (unless otherwise specified).
__all__ = ['get_swap_df', 'lookup_token_name']
# Cell
import pandas as pd
import numpy as np
from .knowledge_graph import Query
from .contracts import whatis
def get_swap_df(skip=None, limit=None):
q = Query()
q.add("MA... |
from dhis.config import Config
from dhis.server import Server
from dhis.types import *
api=Server()
#api=Server(Config(config_file))
#api=Server(Config(config_url))
#api=Server(Config({..}))
api.get("dataElements")
api.get("dataElements",return_type="request")
api.get("dataElements",return_type="json")
api.get("data... |
def download():
print("Download specific file.")
def etl():
print("Run full ETL pipeline on file.")
|
from numpy import *
from numpy.random import *
from LabFuncs import *
from Params import *
from HaloFuncs import *
from WIMPFuncs import *
import pandas
# Halo params
HaloModel = SHMpp
v0 = HaloModel.RotationSpeed
v_esc = HaloModel.EscapeSpeed
beta = HaloModel.SausageBeta
sig_beta = HaloModel.SausageDispersionTensor
s... |
import drned
import pytest
import common.test_here as common
import re
config = {}
def simple_load(name):
def f(p):
p.device.rload("simple_tests/%s" % name)
p.device.dry_run(fname="drned-work/drned-load.txt")
p.device.commit()
return True
return f
config["test-sequence-1"] = [
... |
import argparse
import csv
import os
from lib.tournament import Tournament, MatchResult, PlayerMatchResult, print_pairings, write_scorecard_csv
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Record results')
parser.add_argument('file', type=str, help='path to the tournament file')
... |
# Django
from django.db import models
# Models
from ...utils import PRMModel
# Fields
from django_extensions.db.fields import RandomCharField
class Event(PRMModel):
"""
Represents an event from a calendar, an event is an upcoming situation
of the user, aside from the expected information data, you can a... |
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
#
# 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 ... |
from bolt4ds import flow as d6tflow
import bolt4ds.flow.tasks
import luigi
import pandas as pd
# define 2 tasks that load raw data
class Task1(d6tflow.tasks.TaskPqPandas):
def run(self):
df = pd.DataFrame({'a':range(3)})
self.save(df) # quickly save dataframe
class Task2(Task1):
pass
# d... |
from __future__ import absolute_import, division, print_function, unicode_literals
import HTMLParser
import Queue
import json
import urllib
import urllib2
from echomesh.util import Log
LOGGER = Log.logger(__name__)
ROOT = 'http://search.twitter.com/search.json'
PARSER = HTMLParser.HTMLParser()
def json_to_tweet(tw... |
# -*- coding:utf8 -*-
import time
from lib.unit.Unit import Unit
from lib.unit.Party import Party
from lib.pixel.PixelData import PixelData
from lib.config.SysConfig import SysConfig
from lib.struct.CoordiPoint import CoordiPoint
from lib.control.Control import Control
# 宠物
class Pet(Unit):
def __init__(self):
... |
# Copyright 2019 Matthew Bishop
#
# 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... |
from pinmap import PinMap
pins = PinMap('/proc', 'adc', 6)
def analog_read(channel):
"""Return the integer value of an adc pin.
adc0 and adc1 have 6 bit resolution.
adc2 through adc5 have 12 bit resolution.
"""
with open(pins.get_path(channel), 'r') as f:
return int(f.read(32).split(':')... |
distancia = float(input('qual é a distancia da sua viagem? '))
print('Voce esta prestes a começar uma viagem de {}Km.'.format(distancia))
preco = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('É o preço da sua passagem será de R${:.2f}'.format(preco))
|
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2020. All Rights Reserved.
import sys
from fn_exchange_online.lib.ms_graph_helper import MSGraphHelper
from resilient_lib.components.integration_errors import IntegrationError
if sys.version_info.major == 2:
... |
import argparse
import logging
import os
import pickle
import sys
import numpy as np
import kb
import template_builder
import utils
def get_input(fact, y, template_obj_list,add_ids):
if (add_ids):
x = [fact[0],fact[1],fact[2]]
else:
x = []
for template in template_obj_list:
x.ext... |
from __future__ import print_function
import argparse
import collections
import json
import logging
import os
import random
import time
from abc import abstractmethod
from BCBio import GFF
from Bio import SeqIO
import requests
from six.moves.builtins import next
from six.moves.builtins import object
from six.moves... |
"""
Salidas
Doceavo-->int-->doc
Suma-->int-->suma
"""
doc=0
for a in range(1,13):
if(a>=1):
doc=5*a+1
if(doc==61):
suma=(doc+6)*6
print("a12= "+str(doc))
print("suma= "+str(suma))
elif(a==13):
break
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://publishingstats.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats... |
import io
import json
import re
from collections import defaultdict
from datetime import datetime
from braces.views import JsonRequestResponseMixin
from couchdbkit import ResourceNotFound
from corehq.apps.registration.forms import MobileWorkerAccountConfirmationForm
from corehq.apps.users.account_confirmation import ... |
"""The purpose of this script is to convert the cree "words by frequency"
txt file into a simple word list for the visualization script.
"""
import re
INDIR = "/home/wlane/projects/morph-completion-visualization/data/words/cree_words_by_freq.txt"
OUTDIR = "/home/wlane/projects/morph-completion-visualization/data/word... |
""" Interface class for the LISP-based mReasoner implementation.
"""
import copy
import logging
import os
import platform
import queue
import subprocess
import threading
import time
import urllib.request
import zipfile
import numpy as np
import scipy.optimize as so
FASL_ENDINGS = {
'Darwin': 'dx64fsl',
'W... |
class MacroCommand():
def __init__(self, commands:list):
self.commands = commands
def __call__(self):
for command in self.commands:
command()
macroCommand = MacroCommand()
macroCommand() |
import doctest
import insights.parsers.octavia as octavia_module
from insights.parsers.octavia import OctaviaConf, VALID_KEYS
from insights.tests import context_wrap
CONF_FILE = """
[DEFAULT]
# Print debugging output (set logging level to DEBUG instead of default WARNING level).
debug = False
# Plugin options are hot... |
from datetime import timedelta
from unittest import TestCase
from PyProjManCore.proj_stats import ProjStats
from PyProjManCore.task import Task
class TestProjStats(TestCase):
def test_init(self):
stat = ProjStats()
self.assertIsInstance(stat, ProjStats)
def test_name_constructor(self):
... |
#!/usr/bin/python
import git
import sys
import tempfile
import unidiff
from io import StringIO
from plugins import IBPlugin
class UnfuckPatch(object):
"""
Contains the logic to call plugins that reverts unnecessary changes
to the repository.
>>> unfuck = UnfuckPatch(".")
>>> unfuck.clear()
... |
import os
import sys
from unittest import expectedFailure
from ..utils import TranspileTestCase, NotImplementedToExpectedFailure
class TimeModuleTests(NotImplementedToExpectedFailure, TranspileTestCase):
#######################################################
# _STRUCT_TM_ITEMS
@expectedFailure
def ... |
"""
Proxy a configuration value. Defers the lookup until the value is used, so that
values can be read statically at import time.
"""
import functools
import operator
from staticconf import errors
import six
class UndefToken(object):
"""A token to represent an undefined value, so that None can be used
as a d... |
from uci_comparison import compare_estimators
from sklearn.ensemble.forest import RandomForestClassifier, ExtraTreesClassifier
from rr_forest import RRForestClassifier
from rr_extra_forest import RRExtraTreesClassifier
estimators = {
'RandomForest': RandomForestClassifier(n_estimators=20),
... |
#!/usr/bin/env python3
from collections import Counter
import itertools
class SeatMap:
"""Seat map class."""
def __init__(self, data):
"""Init."""
self.data = data
self.width = len(data[0]) - 1
self.length = len(data) - 1
def render(self, data=None):
"""Render dat... |
"""Standalone tool to print QR codes.
Usage:
QRCodePrinter.py -p=<URL_prefix> -s <nnn> -c <nnn> -o <file>
QRCodePrinter.py -h | --help
QRCodePrinter.py --version
Options:
-p <URL_prefix>, --prefix=<URL_prefix> The URL prefix for the box number
-s <nnn>, --start=<nnn> Starting b... |
from . uuid64 import *
|
import json
import re
from accessstats.client import ThriftClient
REGEX_ISSN = re.compile("^[0-9]{4}-[0-9]{3}[0-9xX]$")
REGEX_ISSUE = re.compile("^[0-9]{4}-[0-9]{3}[0-9xX][0-2][0-9]{3}[0-9]{4}$")
REGEX_ARTICLE = re.compile("^S[0-9]{4}-[0-9]{3}[0-9xX][0-2][0-9]{3}[0-9]{4}[0-9]{5}$")
def _code_type(code):
if not... |
import json
import jsonschema
import typer
from jsonschema import validate
app = typer.Typer()
def get_schema(schema_location):
with open(schema_location, 'r') as schema_file:
schema = json.load(schema_file)
return schema
def get_data(json_data_location):
with open(json_data_location, 'r') as d... |
# ========================================================= #
import requests
import httpx
from typing import Union
from requests.models import Response
from httpx import Response as HttpxResponse
from enum import Enum
# ========================================================= #
class BaseClient:
"""
These ... |
# Generated by Django 2.0.9 on 2018-12-21 01:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('registers', '0012_auto_20181219_1210'),
]
operations = [
migrations.AddField(
model_name='itsys... |
# Generated by Django 2.1.1 on 2019-04-02 00:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0006_private_project_report_snippet'),
]
operations = [
migrations.CreateModel(
name='Community_Private_Report_Snippet',... |
import numpy as np
#import matplotlib as mpl
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.decomposition import PCA
iris = datasets.load_iris(as_frame=True)
X = iris.data.values
y = iris.target.values
print(iris.frame.head(2))
X_reduced_2d = PCA... |
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../..')
from andi_funcs import TrackGeneratorRegression, import_tracks, import_labels, package_tracks
from models import regression_model_2d
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelChe... |
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
# MIT License
#
# Copyright (c) 2021 Nathan Juraj Michlo
#
# 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 Softwar... |
from utils import *
from functools import lru_cache
def parse_nums(s):
return [int(i) for i in s.strip().split(',')]
def part1(values: List[int], DAYS=80) -> int:
@lru_cache
def dfs(v, d):
if d == 0: return 1
return dfs(v-1, d-1) if v else dfs(6, d-1) + dfs(8, d-1)
return sum(dfs(v, ... |
from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton
send_to_friend = 'Регистрируйся на CyberAlleycat от ПЕТУШКИ_СЛАБАЧКИ'
read_the_rules = InlineKeyboardMarkup(row_width=2,
inline_keyboard=[
[InlineKeyboar... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-26 20:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#Warmup-1 > monkey_trouble
def monkey_trouble(a_smile, b_smile):
if a_smile and b_smile:
return True
if not a_smile and not b_smile:
return True
else:
return False |
#art belongs to trinket.io - https://trinket.io/python/02c914e46c
man = (
"""
------
| |
| 0
| /-+-/
| |
| |
| | |
| | |
----------
""",
"""
------
| |
| 0
| /-+-/
| |
| |
| |
... |
from rest_framework import routers
from .views import employeeCreateViewSet
router = routers.SimpleRouter()
router.register(r'employee', employeeCreateViewSet)
urlpatterns = router.urls |
import flopy.mt3d as mt
class SsmAdapter:
_data = None
def __init__(self, data):
self._data = data
def validate(self):
# should be implemented
# for key in content:
# do something
# return some hints
pass
def is_valid(self):
# should be im... |
# Generated by Django 2.1.7 on 2019-05-06 10:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dailies', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='honkaiimpactdaily',
options={'verbos... |
# Copyright 2016 Intel Corporation
#
# 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 wri... |
from __future__ import print_function, division
import sys,os
quspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,quspin_path)
from quspin.operators import hamiltonian
from quspin.basis import spin_basis_general, boson_basis_general, spinless_fermion_basis_general, spinful_fermion_basis_general
import num... |
import scipy
from scipy.io import wavfile
import os
import numpy as np
import glob
from matplotlib import pyplot
GENRES = ["blues", "classical", "country", "disco", "hiphop", "jazz",
"metal", "pop", "reggae", "rock"]
def create_fft(filename):
s_rate, data = scipy.io.wavfile.read(filename) #get sample rate and ... |
"""
Radio button page
clicking them in different order
"""
from pages.base_page import BasePage
import time
from selenium.webdriver.common.by import By
class RadioButtonPage(BasePage):
RADIO_BTN_1 = (By.ID, 'radio-button-1')
RADIO_BTN_2 = (By.XPATH, '/html/body/div/div[2]/input')
RADIO_BTN_3 = (By.XPATH,... |
from numpy.polynomial import polynomial as p
def gcd1(c1,c2):
if(c1[1:]==0.):
return c2;
else:
division=p.polydiv(c2,c1);
return (division[1:],c2);
c1=(1,2,3);
c2=(3,2,1);
#print p.polydiv(c2,c1);
#division=p.polydiv(c2,c1);
#print p.polydiv(c1,c2);
#print division[1:];
#print p.polydiv(c1,c1);
result=g... |
from . import lexer, parser, interpret
import os
print("Welcome to Mathwise. (type '.exit' to exit and '.run' to run the queued lines, '.clear' to clear the console, type '.help' for more info)")
data = ""
while True:
inp = input("mw > ")
if inp.lower().strip() == ".exit":
break
elif inp.lower().s... |
# 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
# distributed under t... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 12 16:51:05 2016
@author: Dominic O'Kane
"""
import numpy as np
from scipy import optimize
from scipy.stats import norm
from ...finutils.FinDate import FinDate
from ...finutils.FinMath import nprime
from ...finutils.FinGlobalVariables import gDaysInYear
from ...finutils... |
from unittest import TestCase
import math
import dexpy.design as design
import numpy as np
import pandas as pd
class TestModelMatrix(TestCase):
"""Tests for generating a model matrix"""
@classmethod
def test_quadratic_model(cls):
"""Test expanding a quadratic model in a rotatable ccd"""
a... |
import os
import datetime
import logging
import random
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import tensorflow as tf
import PIL
from train_data import TrainData
from fractal_gen import FractalGenTensorflowModel
from models_resnet import build_model
logging.basicConfig(
format='[%(asctim... |
""" DAWNets handling """
from builtins import object
from future.utils import with_metaclass
import abc
import os
import sys
import copy
import pprint
import logging
from textx.metamodel import metamodel_from_file
from textx.exceptions import TextXError
from . import dawnyaml
from .. import utils
# TextX schema for... |
'''
Assignment 22 :
In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is
replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be
replaced by D, B would become E, and so on. The method is named afte... |
import tensorflow as tf
import model
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('testing', '', """ checkpoint file """)
tf.app.flags.DEFINE_string('finetune', '', """ finetune checkpoint file """)
tf.app.flags.DEFINE_integer('batch_size', "5", """ batch_size """)
tf.app.flags.DEFINE_float('learning_rate', ... |
from ..filters import FilterByDaterange, FilterByOrder, FilterByStatus, FilterByApplication, FilterByJob
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from saef.models import DatasetSessionMetaData
@login_required()
def dataset_overview(request):
dataset_sessions_me... |
from datetime import datetime, timezone
from freezegun import freeze_time
from app.views.handlers.feedback import FeedbackMetadata, FeedbackPayload
from .conftest import (
case_id,
case_ref,
case_type,
channel,
collection_exercise_sid,
data_version,
display_address,
feedback_count,
... |
class TakoException(Exception):
pass
class TaskFailed(TakoException):
pass
|
# Copyright 2015 Google Inc. 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 law or ag... |
#!/usr/bin/python
import sys
for line in sys.stdin:
data=line.split(" ")
if(len(data)>=5):
reqs=data[5].split("\"")
if len(reqs)>1:
print reqs[1]
|
import pytest
from typeguard import typechecked
from wyrd.constrained_types import ConstrainedInt, add_constraint
@add_constraint(lambda x: x > 0, "must be at least 1")
class Quantity(ConstrainedInt):
pass
@typechecked
def total_quantity(a: Quantity, b: Quantity) -> Quantity:
return Quantity(a + b)
def t... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
# In[2]:
#import data
data = pd.read_csv("D:\dataset_FLD.csv")
# In[3]:
positive = data.loc[data['y']==1]
# In[4]:
negative = data.loc[data['y']==0]
# In[5]:
positive = positive.iloc[:,0:3].values
negative = negativ... |
import string
import sys
import myLib.mySSH as ssh
hostname = 'ev3dev'
port = 22
username = 'robot'
password = 'maker'
client = ssh.connectionSSH(hostname, port, username, password)
isConnected = True
try:
while isConnected:
command = input('Enter command here \n')
command = command.replace('\r',... |
#!/usr/bin/env python3
import sympy
import numpy as np
from scipy.constants import physical_constants
import scipy.sparse as sp
import scipy.sparse.linalg as sla
from types import SimpleNamespace
import kwant
from kwant.continuum import discretize, sympify
import kwant.linalg.mumps as mumps
import time
import argparse... |
import pandas as pd
import config
# Load data dictionary
xls = pd.ExcelFile(config.DATA_DICTIONARY)
# Subset the Excel by selecting relevant columns
df = pd.read_excel(xls, "Data Dictionary (stewards)")[["Name of the ERN",
"Name of the grouping item",
... |
def rev_str(x):
n = len(x)
b = [x[i] for i in range(n-1, -1, -1)]
y = ""
for i in b:
y += i
print (y)
return y
resp = 'y'
while resp == "y":
x = input("Enter string: ")
y = rev_str(x)
resp = input("Conti? (y/n): ").lower() |
'''
Messages to be received by sum nodes
'''
def increment(amount):
'''
:param int amount: An integer amount by which to increment.
'''
return {'type': 'increment', 'amount': amount}
|
"""
03: FOOOF Algorithm
===================
A step by step overview of the FOOOF algorithm.
Note that this notebook is for demonstrative purposes, and does not
represent recommended usage of the FOOOF module.
"""
###################################################################################################
# Al... |
__author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.... |
from .config import get_cors
from .controllers import SocketController
from .route_constants import *
def setup_routes(app, sio, game_app,player_ranking_repository):
socket_controller = SocketController(sio, game_app,player_ranking_repository)
sio.on(CONNECT, socket_controller.on_socket_connected)
sio.on(... |
# coding: utf-8
"""
"""
from .. import db
from .groups import Group
from .users import User
from .objects import Objects
from .permissions import Permissions
__author__ = 'Florian Rhiem <f.rhiem@fz-juelich.de>'
class UserObjectPermissions(db.Model):
__tablename__ = 'user_object_permissions'
object_id = db... |
"""Dictionary with auto-expiring values for caching purposes."""
from time import time
from threading import RLock
from collections import OrderedDict
class ExpiringDict(OrderedDict):
"""Dictionary with auto-expiring values for caching purposes."""
def __init__(self, max_len, max_age_seconds, callback=None)... |
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
for d in range(i - 1, i // 2 - 1, -1):
dp[i] = max(dp[i], max(d, dp[d]) * max(i - d, dp[i - d]))
return dp[n]
|
# Copyright 2015-2017 Yelp 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
"""
BSD 3-Clause License
Copyright (c) 2018, Maël Kimmerlin, Aalto University, Finland
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.