content stringlengths 5 1.05M |
|---|
import cv2
import pyautogui
import os
import copy
import tensorflow as tf
import numpy as np
pyautogui.FAILSAFE=False
FACE_CLASSIFIER_PATH = os.path.realpath(os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'..\\data\\haarcascade_frontalface_default.xml'))
EYE_CLASSIFIER_PATH = os.path.realpath(os.... |
# -*- coding: utf-8 -*-
__version__ = '0.16.1.dev0'
PROJECT_NAME = "planemo"
PROJECT_USERAME = "galaxyproject"
RAW_CONTENT_URL = "https://raw.github.com/%s/%s/master/" % (
PROJECT_USERAME, PROJECT_NAME
)
|
from django.test import TestCase
from mock import Mock
from lazysignup.models import LazyUser
class LazyUserManagerTests(TestCase):
"""
Tests for LazyUserManager
"""
def test_generate_username_no_method(self):
"""
Tests auto generated UUID username
"""
mock_user_class ... |
"""
Volume PairList provider
Provides dynamic pair list based on trade volumes
"""
import logging
from functools import partial
from typing import Any, Dict, List
import arrow
from cachetools.ttl import TTLCache
from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes... |
import pytest
from search.factory import TicketFactory
from search.views import InvalidSearchTermException, Search
@pytest.mark.django_db
def test_ticket_search_for_no_matching_data():
TicketFactory(_id='ticket 1')
search = Search(search_term='_id', search_value='No Match')
qs = search.search_tickets()
... |
"""The builtin int type (W_AbstractInt) and the base impl (W_IntObject)
based on rpython ints.
In order to have the same behavior running on CPython, and after RPython
translation this module uses rarithmetic.ovfcheck to explicitly check
for overflows, something CPython does not do anymore.
"""
import operator
import ... |
import abc
import decimal
import json
import warnings
from optuna import type_checking
if type_checking.TYPE_CHECKING:
from typing import Any # NOQA
from typing import Dict # NOQA
from typing import Sequence # NOQA
from typing import Union # NOQA
CategoricalChoiceType = Union[None, bool, int,... |
from typing import Optional, Callable
from . import constants as C
import mxnet as mx
def get_kl_divergence(distribution_name: str) -> Callable:
if distribution_name == C.DIAGONAL_GAUSS:
return diagonal_gaussian_kl
else:
raise ValueError("Unsupported distribution")
def diagonal_gaussian_kl(... |
import configparser
import os
from subprocess import PIPE, Popen
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ObjectList(list):
"""a way to store vars on a list"""
pass
class ChangeHandler(FileSystemEventHandler):
def __init__(self, *args,... |
# Prepare bodymap will parse labels from the FMA
# - including terms likely to be found in social media
from PyDictionary import PyDictionary # pip install PyDictionary
from svgtools.generate import create_pointilism_svg
from svgtools.utils import save_json
from nlp import processText # nlp module from wordfish
from ... |
import base64
import ujson as json
import numpy as np
import os
import mmap
import codecs
def gzip_str(str):
return codecs.encode(str.encode('utf-8'), 'zlib')
# return gzip.compress(str.encode('utf-8'))
def gunzip_str(bytes):
return codecs.decode(bytes, 'zlib').decode('utf-8')
# return gzip.decompre... |
import numpy as np, json
import pickle, sys, argparse
import keras
from keras.models import Model
from keras import backend as K
from keras import initializers
from keras.optimizers import RMSprop
from keras.utils import to_categorical
from keras.callbacks import EarlyStopping, Callback, ModelCheckpoint
from keras.laye... |
# coding: utf-8
# In[3]:
import random
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123)
np.random.rand()
# In[4]:
def individual(popSize):
return list(np.random.choice([0,1],popSize))
# In[5]:
def population (popSize,chromLeng):
return [individual(popSize) for x in range(chromL... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-26 13:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('potrait', '0004_image_name'),
]
operations = [
migrations.RemoveField(
... |
import numpy as np
import sys
input = int(sys.argv[1])
def prediction(gene_distance):
w_1 = -8.15392002*pow(10, -7)
b = 0.1874616
w_2 = -0.6294551
w_3 = 0.3701174
first_layer = np.tanh(gene_distance*w_1)
pred_1 = first_layer*w_2 + b
pred_0 = first_layer*w_3 + b
return(pred_1, pred_0)
... |
#!/usr/bin/env python3
import sys
def restore(archive, D, x, y):
for V in archive:
print(*V)
def diff(t1, t2):
N = len(t1)
M = len(t2)
MAX = M + N
zp = MAX
state = [(0,)] * (2 * MAX + 1)
archive = []
for D in range(MAX + 1):
for k in range(-D, D + 1, 2):
i... |
"""Fit a classifier based on input train data.
Save the models and coefficients in a table as png.
Usage: train.py [--data_file=<data_file>] [--out_dir=<out_dir>]
Options:
[--data_file=<data_file>] Data set file train are saved as csv.
[--out_dir=<out_dir>] Output path to save model, tables and image... |
# -*- coding: utf-8 -*-
from ..syntax import macros, test, test_raises, fail # noqa: F401
from ..test.fixtures import session, testset
from ..funutil import Values
from ..seq import (begin, begin0, lazy_begin, lazy_begin0,
pipe1, pipe, pipec,
piped1, piped, exitpipe,
... |
from setuptools import setup # type: ignore
CLASSIFIERS = """\
Development Status :: 5 - Production/Stable
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Programming Language :: Python
Programming Language :: Python :: 3.7
Programming Language ... |
N = int(input())
ans = 0
f = 2
s = 3
for i in range(N - 2):
ans += (1 * f * s)
f = s
s += 1
print(ans)
|
import time
import itertools
from testbase import con, cur
BATCH = 500
for num in itertools.count():
for x in range(BATCH):
n = (num * BATCH) + x
cur.execute("insert into foo values (?, ?)",
(n, "string-value-of-"+str(n)))
con.commit()
print num, 'write pass complete', ... |
# Generated by Django 3.0 on 2020-06-12 13:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webapp', '0005_raffle_active'),
]
operations = [
migrations.AlterModelOptions(
name='blog',
options={'ordering': ['-date_poste... |
# Generated by Django 3.2.8 on 2021-11-06 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20211103_2205'),
]
operations = [
migrations.AlterField(
model_name='user',
name='phone_no',
... |
from django.contrib import admin
from .models import Game, Play
@admin.register(Game)
class GameAdmin(admin.ModelAdmin):
list_display = ('id', 'first_player', 'second_player', 'type', 'uuid')
@admin.register(Play)
class PlayAdmin(admin.ModelAdmin):
list_display = ('turn', 'x', 'y', 'first_score', 'second_s... |
from logs import logDecorator as lD
import json
import numpy as np
import tensorflow as tf
from datetime import datetime as dt
import matplotlib.pyplot as plt
from lib.NNlib import NNmodel
from lib.GAlib import GAlib
config = json.load(open('../config/config.json'))
logBase = config['logging']['logBase'] + '.m... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2021 CERN.
#
# Invenio-Vocabularies is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Test the affiliation vocabulary service."""
import pytest
from invenio_... |
import lxml.etree
import sieve.operators as ops
from nose.tools import raises
@raises(AssertionError)
def test_assert_eq_xml():
ops.assert_eq_xml("<foo></foo>", "<bar></bar>")
def test_eq_xml():
b = "<foo><bar>Value</bar></foo>"
c = """
<foo>
<bar>
Value
</bar>
</foo>
"""
assert ops.... |
# Copyright 2020 AUI, Inc. Washington DC, USA
#
# 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 ... |
while True:
numeros = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco',
'seis','sete', 'oito', 'nove', 'dez', 'onze', 'doze',
'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete',
'dezoito', 'dezenove', 'vinte')
num = int(input('Digite um numero de 0 a 20: '))
... |
#!/usr/bin/env python
"""An in memory database implementation used for testing."""
import os
import sys
from grr.lib import rdfvalue
from grr.lib import utils
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import objects
from grr.server.grr_response_server import db
class InMemoryDB(db.Da... |
import time
import serial
import sys
# this port address is for the serial tx/rx pins on the GPIO header
SERIAL_PORT = '/dev/ttyUSB1'
# be sure to set this to the same rate used on the Arduino
SERIAL_RATE = 9600
def main():
ser = serial.Serial(SERIAL_PORT, SERIAL_RATE)
for line in sys.stdin:
print(li... |
# -*- coding: utf-8 -*-
import os
import hotshot
import hotshot.stats
#import test.pystone
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
args = '<path/to/profiling-file.prof>'
help = u"Génération de statistiques à partir d'un fichier du profi... |
# - snd X plays a sound with a frequency equal to the value of X.
# - set X Y sets register X to the value of Y.
# - add X Y increases register X by the value of Y.
# - mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y.
# - mod X Y sets register X to the remainder ... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for IssueTracker object."""
# pylint: disable=too-many-instance-attributes
from ggrc import db
from ggrc.integrations import constants
from ggrc.models.mixins import base
from ggrc.models.mixins ... |
# Generated by Django 2.2 on 2019-08-07 09:41
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("audits", "0012_auto_20190724_1157")]
operations = [
migrations.AddField(
model_name="auditstatushis... |
class Bunsetsu:
def __init__(self, morps):
self.morphologies = morps
self.surface = "".join([morp.surface for morp in morps])
def ispredicate(self):
return any([morp.part_of_speech in ["動詞", "形容詞", "判定詞"]
for morp in self.morphologies])
|
from os.path import splitext
from typing import Union
import cv2
import numpy as np
from platonic_io import logger
from .local_utils import detect_lp
def load_model(path):
from keras.models import model_from_json # long running import
try:
path = splitext(path)[0]
with open("%s.json" % pa... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def game():
import pygame, sys, pygame.mixer
from pygame.locals import *
import common_pygame
import enemy
import load_resources
import random
import ship
import background
import hud
import bonus
import menu
import effects
import particles
import smoke
import... |
# Generated by Django 3.1.2 on 2020-10-27 02:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Album',
fields=[
... |
# -*- coding: utf-8 -*-
"""Models for API requests & responses."""
import dataclasses
import datetime
from typing import Optional, Type
import marshmallow_jsonapi
from ...tools import dt_days_left, dt_parse
from .base import BaseModel, BaseSchema, BaseSchemaJson
class SystemSettingsSchema(BaseSchemaJson):
"""Pa... |
from openpnm.phases.mixtures import IdealGas, species
import openpnm.models as mods
from openpnm.utils import logging
logger = logging.getLogger(__name__)
class DryAir(IdealGas):
r"""
"""
def __init__(self, network, **kwargs):
super().__init__(network=network, components=[], **kwargs)
N2... |
DAILY_URI = "dailyData/"
COUNTY_URI = "byCounty/"
STATE_URI = "byState/"
|
import ifcopenshell
import ifcopenshell.geom as geom
from topologic import Vertex, Edge, Wire, Face, Shell, Cell, CellComplex, Cluster, Topology, Graph, Dictionary, Attribute, AttributeManager, VertexUtility, EdgeUtility, WireUtility, ShellUtility, CellUtility, TopologyUtility
import cppyy
def edgesByVertices(vertice... |
"""
Function for filter that ranks items (edges of graph) by co-occurrence
by sending batch queries to the MRCOC co-occurrence API
Parameters:
G - A networkX graph
count - number of nodes to return (default=50)
Returns:
A networkX subgraph with 'count' number of unique edges
Number of edges betwee... |
#!/user/bin/env python
'''notFilter.py
This filter wraps another filter and negates its result
'''
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@gmail.com"
__version__ = "0.2.0"
__status__ = "done"
class NotFilter(object):
'''Constructor takes another... |
import pandas as pd
from pandas.core.dtypes.common import is_datetime64_any_dtype as is_datetime
from utils.utils import isna
def block(df, index, reason):
print(f"Blocking new row {index}, reason: {reason}")
df.drop(index, inplace=True)
def modify(df, index, column, old_value, new_value):
col = df[col... |
def get_unique(arr: list) -> list:
return list(set(arr)) |
namaFile = str(input("Masukkan nama file: "))
#namaFile = "/home/icaksh/Coolyeah/Python-Projects-Protek/Chapter 07/Latihan/contohfile.txt"
try:
fopen = open(namaFile, "r")
print(fopen.read())
except FileNotFoundError:
print("File tidak ditemukan, apakah lokasi file sudah benar") |
from abc import ABC, abstractmethod
import torch
from .. import utils
from envs.babyai import Bot
from random import Random
class Agent(ABC):
"""An abstraction of the behavior of an agent. The agent is able:
- to choose an action given an observation,
- to analyze the feedback (i.e. reward and done state)... |
from azure.keyvault import KeyVaultClient
from azure.common.credentials import ServicePrincipalCredentials
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
from cryptogr... |
# classes for adding modifications to images during training
# such as the zoom in stuff
# or masking parts of original image onto currently generated image
# TODO: these are all directly modifying their generation job, i dont like that, but it'll have to be refactored later
from typing import List
from src import Gen... |
"""mock utilities for testing
Functions
---------
- mock_authenticate
- mock_check_account
- mock_open_session
Spawners
--------
- MockSpawner: based on LocalProcessSpawner
- SlowSpawner:
- NeverSpawner:
- BadSpawner:
- SlowBadSpawner
- FormSpawner
Other components
----------------
- MockPAMAuthenticator
- MockHub
-... |
from collections import OrderedDict
import yaml
class UnsortableList(list):
def sort(self, *args, **kwargs):
pass
class UnsortableOrderedDict(OrderedDict):
def items(self, *args, **kwargs):
return UnsortableList(OrderedDict.items(self, *args, **kwargs))
yaml.add_representer(UnsortableOrder... |
from django.utils.translation import ungettext, ugettext as _
from django.core.urlresolvers import reverse
from django.db.models import F
from django.contrib import messages
from forum.models.action import ActionProxy
from forum.models import Award, Badge, ValidationHash, User
from forum import settings, REQUEST_HOLDER... |
"""
Set up the plot figures, axes, and items to be done for each frame.
This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as... |
import json
import logging
from .google_geocoding_service import GoogleGeocodingService
from .here_geocoding_service import HereGeocodingService
logger = logging.getLogger(__name__)
CREDENTIALS_FILE = "geoservice_credentials.json"
class GeocodingServiceBuilder:
@staticmethod
def build_geocoding_services():... |
from base64 import urlsafe_b64encode
import azure.functions.blob as blob
import azure.functions as fn
import logging
import time
import dill
def info(msg: str):
logging.info(f"executor: {msg}")
def executor(
input: dict,
inputCtx: blob.InputStream, # TODO: load pickle into user namespace.... |
import torch.nn as nn
from collections import OrderedDict
import torch.nn.functional as F
import torch
class BasicBlock(nn.Module):
expansion = 1
def __init__(
self,
inplanes,
planes,
stride=1,
downsample=None,
groups=1,
base_width=64,
dilation=... |
#!/usr/bin/env python
import os
import sys
import bed
import generalUtils
import argparse
import random
parser = argparse.ArgumentParser(description='count strings')
parser.add_argument('-i', required= True, help='input')
parser.add_argument('-o', required= True, type = argparse.FileType('w'), help='output')
parser.ad... |
'''
This is the project for children programming
This project is made by Jack Shi
project description:
1. help info
2. list all student info
3. add student info
4. remove student info
5. modify student info
6. check student info
file format:
v1.0 using txt file with each student in ench line info is split by ,
for ins... |
import os
import sys
from astropy.io import ascii
import datetime
from modules.visfunc import *
###################################################################
# RA/DEC conversions
def ra2dec(ra):
if not ra:
return None
r = ra.split(':')
if len(r) == 2:
r.append(0.0)
# Deal with when RA is actually H... |
import unittest
from kmy.kmy import Kmy
file_name = 'Test.kmy'
class TestUser(unittest.TestCase):
def setUp(self):
mm = Kmy.from_kmy_file(file_name)
self.user = mm.user
def test_read_name(self):
self.assertEqual('Your name', self.user.name)
def test_read_email(self):
sel... |
# Example 3
import csv
# Indexes of some of the columns
# in the dentists.csv file.
COMPANY_NAME_INDEX = 0
NUM_EMPLOYEES_INDEX = 6
NUM_PATIENTS_INDEX = 7
def main():
# Open a file named dentists.csv and store a reference
# to the opened file in a variable named dentists_file.
with open("E:/GitHub/2021-c... |
import py.path
import pytest
__all__ = ["intercept_url", "intercept_skip_conditions"]
@pytest.fixture
def intercept_url(request):
if not request.param:
pytest.skip("got empty parameter set")
return request.param
@pytest.fixture(scope="function")
def intercept_skip_conditions(request):
"""
P... |
import unittest
from slixmpp.test.integration import SlixIntegration
class TestConnect(SlixIntegration):
async def asyncSetUp(self):
await super().asyncSetUp()
self.add_client(
self.envjid('CI_ACCOUNT1'),
self.envstr('CI_ACCOUNT1_PASSWORD'),
)
self.add_clien... |
import string
SUPPORTED_TEMPLATE_ENGINES = frozenset(['simple', 'mako', 'jinja2', 'genshi'])
BASE_DEFAULT_TEMPLATE = '''<!DOCTYPE HTML>
<html>
<head>
<title>{title}</title>
{head}
</head>
<body>
{content}
</body>
</html>'''
DEFAULT_SIMPLE_TEMPLATE = BASE_DEFAULT_TEMPLATE.format(
title='${titl... |
from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import Client
from api.models import Deck, Flashcard
class FlashcardsTestCase(TestCase):
def setUp(self):
self.user_name = 'user1'
self.user_pass = 'pass1'
self.... |
"""Env wrappers"""
from gym import ActionWrapper, Wrapper, logger
from gym.spaces import Discrete, Box
import numpy as np
class WrapPendulum(ActionWrapper):
""" Wrap pendulum. """
@property
def action_space(self):
return Discrete(2)
@action_space.setter
def action_space(self, value):
... |
import sys,os
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from src import models
from src import others
from src import distributed
from src import preprocess
from src import train |
#!/usr/bin/env python3
from itertools import combinations
with open('input.txt') as f:
for line in f:
line = line.strip().split('-')
number = int(line[-1][:line[-1].find('[')])
newstr = ' '.join(map(lambda word: ''.join(map(lambda x: chr((ord(x) - ord('a') + number) % 26 + ord('a')), wor... |
from jdaviz.configs.specviz.plugins.redshift_slider import redshift_slider as rs
def test_bounds_orderly_new_val_greater_than(specviz_app, spectrum1d):
label = "Test 1D Spectrum"
specviz_app.load_spectrum(spectrum1d, data_label=label)
redshift_slider = rs.RedshiftSlider
redshift_slider.max_value = 10... |
name = "S - Grid Squares - Filled"
description = "Grid of filled oscillating squares"
knob1 = "X Offset"
knob2 = "Y Offset"
knob3 = "Size"
knob4 = "Color"
released = "March 21 2017"
|
"""Support for Panasonic sensors."""
import logging
from homeassistant.const import CONF_ICON, CONF_NAME, TEMP_CELSIUS, CONF_TYPE
from homeassistant.helpers.entity import Entity
from . import DOMAIN as PANASONIC_DOMAIN, PANASONIC_DEVICES
from .const import (
ATTR_INSIDE_TEMPERATURE,
ATTR_OUTSIDE_TEMPERATURE,... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/EffectEvidenceSynthesis) on 2019-01-25.
# 2019, SMART Health IT.
##
from . import domainresource
class EffectEvidenceSynthesis(domainresource.DomainResource):
""" A quantified estimat... |
# Copyright 2016 Mirantis 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... |
from .wkw import Header, Dataset, File
__ALL__ = ["Header", "Dataset", "File"]
|
#!/usr/bin/env python3
import pandas as pd
from nsepython import *
from datetime import datetime
from Bwebdwnldpkg import *
Holiday_list = pd.json_normalize(nse_holidays()['FO'])
nonTradedays= str(Holiday_list.tradingDate)
#print (nonTradedays)
t_day = datetime.today().strftime('%d-%b-%Y')
day_num = datetime.to... |
"""
File: flask_http2_push.py
Exposes a decorator `http2push` that can be used on
Flask's view functions.
@app.route('/')
@http2push()
def main():
return 'hello, world!'
"""
import json
import flask
import functools
__author__ = 'David Aroesti'
PUSH_MANIFEST = 'push_manifest.json'
manifest_ca... |
from __future__ import absolute_import
from django.conf import settings
from celery import Celery
import os
# Allow run administrative tasks like manage.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")
# Celery app declaration
func = Celery('main')
# Setup
func.config_from_object('django.conf:sett... |
# 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"); you may not u... |
from enum import Enum
import boto.ec2
from boto.exception import EC2ResponseError
from . import di
class TagStatus(Enum):
correct = 1
incorrect = 2
missing = 3
INSTANCE_ID_NOT_FOUND = 'InvalidInstanceID.NotFound'
class InstanceNotFound(Exception): pass
def _get_boto_error_type(exception):
errors =... |
import math
import random
import numpy as np
import copy
def ackley(x,y):
return -20*math.exp(-0.2*math.sqrt(0.5*(x**2 + y**2)))-math.exp(0.5*(math.cos(2*3.1415*x) + math.cos(2*3.1415*y)))+math.exp(1)+20
class State:
x = 0
y = 0
solution = 0
def __init__(self,x,y,func):
self.x = x
self.y = y
self.solutio... |
# Copyright 2016-2021 Doug Latornell, 43ravens
# 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 t... |
# Copyright 2013-2022 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.package import *
class PyDbfread(PythonPackage):
"""DBF is a file format used by databases such dBase, Vi... |
from dataclasses import dataclass
from typing import Optional
from apischema.json_schema import deserialization_schema
@dataclass
class Node:
value: int
child: Optional["Node"] = None
assert deserialization_schema(Node) == {
"$schema": "http://json-schema.org/draft/2020-12/schema#",
"$ref": "#/$def... |
# -*- coding: utf-8 -*-
__author__ = """Christoph Rist"""
__email__ = "c.rist@posteo.de"
import tensorflow as tf
def assert_normalized_quaternion(quaternion: tf.Tensor):
with tf.control_dependencies(
[
tf.debugging.assert_near(
tf.ones_like(quaternion[..., 0]),
... |
# -*- coding: utf-8 -*-
from . import GenericCommand
from ...models import Journal
from ...tasks import process_journal, journal_forward
class Command(GenericCommand):
''' paloma postfix management
'''
option_list = GenericCommand.option_list + ()
''' Command Option '''
def handle_process(self, ... |
import numpy as np
class FlowExceedance:
def __init__(self, start_date, end_date, duration, exceedance):
self.start_date = start_date
self.end_date = end_date
self.duration = duration
self.flow = []
self.exceedance = exceedance
self.max_magnitude = None
def add... |
#!/usr/bin/env python3
"""
Copyright (c) 2021, SunSpec Alliance
All Rights Reserved
"""
import sys
import time
import sunspec2.modbus.client as client
import sunspec2.file.client as file_client
from optparse import OptionParser
"""
Original suns options:
-o: output mode for data (text, xml)
-x: e... |
# Copyright Raimar Sandner 2012-2020.
# Copyright András Vukics 2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)
## @package testdriver
# This is the Python testdriver for the \ref testsuite.
#
# It is intended to be used with the CMake CTest utility.
# When called w... |
from __future__ import absolute_import
import datetime
import pytz
from django.test import TestCase
from django.utils.html import escape
from schedule.models import Event, Rule, Calendar
from schedule.periods import Period, Day
from schedule.templatetags.scheduletags import querystring_for_date, prev_url, next_url, c... |
#http://stackoverflow.com/questions/16908186/python-check-if-list-items-are-number
#http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python
t = int(input())
while t:
a = input()
lis=[str(x) for x in input().split()]
lis.remove('+');
lis.remove('=');
for x in range(0,3):
if li... |
# """
# tests.test_repressor
#
# TODO: WORDS GOOD PLEASE.
#
# W.R. Jackson 2020
# """
#
# import pytest
#
#
# from ibis.scoring.cello_score import (
# CelloRepressor,
# optimize_repressor,
# )
#
# # -------------------------------- Test Fixtures -------------------------------
# @pytest.fixture
# def generate_s... |
import numpy as np
import matplotlib.pyplot as plt
from time import sleep
import os
import json
from flask import Flask
from flask_cors import CORS
from flask import jsonify
from flask import request
app = Flask(__name__)
CORS(app)
@app.route("/", methods=['GET'])
def question():
return jsonify(
api = 'P... |
# In this script, we read the json file from an S3 location
# Use the flatten() function to get the nested json schema into column names
from pyspark.sql import types as T
import pyspark.sql.functions as F
from pyspark.sql import SparkSession
from pyspark.sql.utils import AnalysisException
from pyspark.sql.functions i... |
import sys
import logging
def createLogger():
"""
Function to create a Logger for logging.
"""
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [stdout_handler]
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s -... |
"""Tests for the column parser in the create_table file
"""
from unittest import TestCase
from nose.tools import eq_
from ..create_table import get_column_parser
class TestCreateTableStatement(TestCase):
"""Tests for the column parser
"""
@staticmethod
def test_basic():
"""Tests the parser ca... |
# -*- coding: utf-8 -*-
"""
Practical Algorthns
Problem set: Unit 3, set 8.2
Problem statement:
2) What was a bonus problem before is now just a problem; so: Implement a Queue based on the doubly linked list from Problem set 6.2. You should provide a "push" and "pop" interface. You should re-use the Doubly Linke... |
#!/usr/bin/env python
import os, sys
try:
from pathlib2 import Path
except ImportError:
from pathlib import Path
from clckwrkbdgr import xdg
from clckwrkbdgr import commands
import clckwrkbdgr.jobsequence.context
trace = context = clckwrkbdgr.jobsequence.context.init(
verbose_var='DOTFILES_SETUP_VERBOSE',
skip_pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.