content stringlengths 5 1.05M |
|---|
# Copyright 2017 The TensorFlow 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 applicab... |
import json
from redict import JsonRemapper
class TestJsonRemapper:
def setup(self):
self.data = {
'aaa': {
'bbb': [
{
'ccc': [
{
'ddd': 123,
... |
import pytest
from calculator.calculator import Calculator
c = Calculator()
def test_sum():
assert c.sum(1, 1) == 2
def test_subtract():
assert c.subtract(0, 1) == -1
def test_multiply():
assert c.multiply(10, 0) == 0
def test_division():
assert c.divide(1, 0) == 'Can not divide by zero.'
de... |
from setuptools import setup, find_packages
setup(
name='tracking_analysis',
version='0.01',
packages=["tracking_analysis"],
url='',
license='',
author='Michael Capizzi',
author_email='mcapizzi@email.arizona.edu',
description='Using tracking data from opendata'
)
|
# Fazendo login em um site de forma automática.
from selenium import webdriver
import time
browser = webdriver.Firefox()
browser.get("https://sistema.justwebtelecom.com.br/login.php")
time.sleep(2)
username = browser.find_element_by_id("email")
password = browser.find_element_by_id("senha")
username.send_keys("MEU-... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import texterra
import types
import six
from os import getenv
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
# Texterra Tests
class CustomTexterraAPITest(unittest.TestCase):
def setUp(self):
TEXTERRA_... |
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# LOAD PACKAGES
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
trainimgs = mnist.train.images
trainlabels = mnist.trai... |
from flask import Flask, jsonify, render_template, request, redirect, url_for
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import load_model
from werkzeug.utils import secure_filename
import numpy as np
import shutil
import time
app = Flask(__name_... |
# Copyright (c)
# projectName: nlpdoad # filename : momentum.py
# Author: weihangzhang # email: hannah.zz@qq.com
# createDate : 2019/5/8 下午8:45
# lastModified: 2019/5/8 下午8:45
# desc: momentum是动量的意思,
import numpy as np
class Momentum:
def __init__(self, lr=0.1, momentum=0.9):
self.lr... |
import numpy as np
class Perceptron:
"""
Perceptron single layer neural network is implemented in this script.
Please find the explanation for the code in the link provided in the README of the repo
"""
def __init__(self, eta=0.01, random_state=1, epochs=50):
"""
:par... |
from django.contrib import admin
from .models import DetailedPrediction, DetailedPredictionWarning
# Register your models here.
# @admin.register(RoughPrediction)
# class RoughPredictionAdmin(admin.ModelAdmin):
# pass
@admin.register(DetailedPrediction)
class DetailedPredictionAdmin(admin.ModelAdmin):
list_... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
# 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.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use thi... |
import re
import sys
import traceback
import platform
import subprocess
import config
import ansible_runner
from io import StringIO
def get_leases():
print("[INFO] Fetching current leases from ZTP dhcp")
already_in_list = []
leases_list = []
pattern = re.compile(
r"lease ([0-9.]+) {.*?hardwar... |
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from orders.models import Order
from reviews.models import Review, ReviewImage, OwnerComment
class ReviewImageSerializer(serializers.ModelSerializer):
class Meta:
mo... |
import pandas as pd
import numpy as np
import backtrader as bt
from scipy.signal import argrelextrema
from positions.securities import get_security_data
class Extrema(bt.Indicator):
'''
Find local price extrema. Also known as highs and lows.
Formula:
- https://docs.scipy.org/doc/scipy/referen... |
from distutils.core import setup
setup(
name = 'hasel',
packages = ['hasel'],
version = '1.0.1',
description = 'python+numpy RGB to HSL (and vice versa) converter',
author = 'Dimas Sumartoyo',
author_email = 'dimas.gs@outlook.com',
url = 'https://github.com/sumartoyo/hasel',
download_url... |
import numpy as np
import torch
from pymde import constraints
from pymde import preprocess
from pymde import recipes
from pymde import util
from pymde.functions import penalties
import pymde.testing as testing
def test_k_nearest_neighbors():
data_matrix = np.array([[0.0], [1.0], [1.5], [1.75]])
graph = prepr... |
# Crie um programa que:
# Crie uma matriz de dimensão 3x3
# Preencha a matriz com valores lídos pelo teclado
# No final, mostre a matriz na tela, com a formatação correta
matriz = [ [ 0, 0, 0 ] , [ 0, 0, 0 ] , [ 0, 0, 0 ] ]
for linha in range(0, 3):
for coluna in range(0, 3):
matriz [linha] [coluna] =... |
#!/usr/bin/env python3
import argparse
import glob
import os
import pathlib
import requests
import shutil
import subprocess
import sys
import zipfile
def get_args():
return None
def cmd_exists(name):
if not name:
raise TypeError("'name' not provided!")
if not shutil.which(name):
return Fa... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
"""
Helper classes and functions for the RESP program.
Assists in generating van der Waals surface, computing the electrostatic
potential with Psi4, and adding constraints for two-stage fitting procedure.
"""
__authors__ = "Asim Alenaizan"
__credits__ = ["Asim Alenaizan"]
__copyright__ = "(c) 2014-2018, The P... |
# -*- coding: utf-8 -*-
import os
from artifacts import errors as artifacts_errors
from artifacts import reader as artifacts_reader
from artifacts import registry as artifacts_registry
from dfvfs.lib import errors as dfvfs_errors
from dfvfs.path import factory as path_spec_factory
from dfvfs.helpers import file_syste... |
'''
简单的搜索引擎
1) 数据来源,爬虫
起点
url :http://site.baidu.com/
2) 起点页面 url
页面的内容
页面中的超链接
3) 抓取超链接的各个页面 url
页面的内容
页面中的超链接
'''
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import re
# 抓取起点
# url = 'http://site.baidu.com/'
urls = ['http:/... |
from setuptools import setup
setup(name='donkeyturbo',
version='0.1',
description='Extension for donkeycar module',
url='http://github.com/r7vme/donkeyTurbo',
author='Roma Sokolkov',
author_email='rsokolkov@gmail.com',
license='MIT',
packages=['donkeyturbo'],
zip_safe=Fa... |
import abc
import numpy as np
from rlkit.data_management.path_builder import PathBuilder
from rlkit.envs.remote import RemoteRolloutEnv
from rlkit.misc.ml_util import ConstantSchedule
from rlkit.state_distance.exploration import MakeUniversal
from rlkit.state_distance.rollout_util import MultigoalSimplePathSampler, \... |
# 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 th... |
#!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
class Hear_orders:
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publi... |
import re
import weakref
from io import BytesIO
from uuid import uuid4
from xml.etree import cElementTree as ElementTree
from collections import defaultdict
import six
from casexml.apps.case.mock import CaseBlock, CaseFactory, CaseStructure
from casexml.apps.case.xml import V1, V2, V2_NAMESPACE
from casexml.apps.phon... |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
import os
import py
import pytest
import qisys.script
import qisys.sh
import qisrc.git
from qisrc.test.conftest import TestGitWorkTree, TestGit
from q... |
# Generates two lists of digits assembled from four random 3-digit primes
# and outputs them to stdout. Each is output as a csv on its own line,
# representing the initial state of stack0 and stack1
import random
import math
def shuffle(nums):
for i in range (len(nums)):
choice = random.randint(0, len(nums)-1)
... |
import logging
import os
from hazelcast.core import CLIENT_TYPE
from hazelcast.invocation import Invocation
from hazelcast.protocol.codec import client_statistics_codec
from hazelcast.util import current_time_in_millis, to_millis, to_nanos, current_time
from hazelcast import six, __version__
try:
import psutil
... |
"""
The MIT License (MIT)
Copyright (c) 2013 Niko Skrypnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge... |
# Generated by Django 3.2.4 on 2021-09-15 17:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_registry', '0033_collection_source_url'),
]
operations = [
migrations.AddField(
model_name='collection',
name='... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import time
from scipy import stats, linalg
#Huseyin DALBUDAK
# NOV. 11 2017
# Non-linear Gauss fitting
def feval(funcName, *args):
return eval(funcName)(*args)
def fitresult( iter,sse,lambda_,n,p,yfit,r,sig,J):
iterations = iter
phi ... |
# def leastNumSquares(num):
# #Because of Lagrange's four square theorem, the max number can be 4
# if(isSquare(num)):
# return 1
# # If num is not in the form of 4^k*(8*m + 7), due to Legendres theorem
# while(n % 4 = 0):
def leastNumSquares(num):
if(num <= 0):
return 0
... |
#!/usr/bin/python
# Copyright (C) Vladimir Prus 2005.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Tests that we can declare a rule in Jamroot that will be can be called in
# child Jamfile to declare ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Program: Rotate 2D array perpendicular to the plane
Version: 20210601
@author: Pranab Das (GitHub: @pranabdas)
"""
def rotate_2d(data, rotation, x, y):
import numpy as np
from scipy import interpolate
data[np.isnan(data)] = 0
rotation = np.deg2rad(rota... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Miscellaneous utility functions for cache
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from __future__ import ab... |
import logging
import sys
import unittest
import appium
import mock
from AppiumLibrary.keywords import _ApplicationManagementKeywords
from webdriverremotemock import WebdriverRemoteMock
logger = logging.getLogger()
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
stream_handler = l... |
from art.attacks.evasion import ProjectedGradientDescent
import numpy as np
class PGDPatch(ProjectedGradientDescent):
def __init__(self, estimator, **kwargs):
super().__init__(estimator=estimator, **kwargs)
assert (
not self.estimator.channels_first
), "This attack currently on... |
from search_function import search_users
import os
f = open(os.path.abspath('token.txt'),'r')
token_vk = f.read()
def gate_function(town,sex,token=token_vk):
town = town[:13]
print(token)
return search_users(town,sex,token)
f.close()
|
# The following strategies have been learned as successful against the Great Firewall.
WORKING_STRATEGIES = [
{
"strategy" : "\/",
"success_rate" : .03,
"description" : "No strategy",
"test_type" : "http",
"server_side" : False,
"country" : "china"
}... |
import numpy as np
from PIL import Image
from IPython.display import display
from IPython.display import Image as ImageDisplay
from io import BytesIO
def output_to_pil(output_tensor):
x = output_tensor.squeeze().cpu().detach().numpy()
x = (x - np.min(x)) / (np.max(x) - np.min(x)) * 255
return Image.fromar... |
# Copyright (c) 2021 VisualDL Authors. All Rights Reserve.
#
# 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... |
#!/usr/bin/env python
import sys
from pathlib import Path
if __name__ == '__main__':
sys.path.append(str(Path(__file__).parent.parent.resolve()))
from app.bootstrap.configmanager import ConfigManager
ConfigManager.load_config()
argc = len(sys.argv)
if argc == 2:
print(ConfigManager.get(sys... |
import os
import sys
from django.conf import settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF='testurlconf',
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
... |
from student import Student
# inherit from Student class
class HighSchoolStudent(Student):
school_name = "Nash tech"
def get_school_name(self):
return "this is high scholl student"
def get_name_capitalize(self):
original_value = super().get_name_capitalize()
return original_value ... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import routers, permissions
from .analysis_models.viewsets import AnalysisMo... |
'''
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
'''
import math
class Solution(object):
def isPerfectSquare(self, num... |
#!/usr/bin/env python3
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
import re
from argparse import ArgumentParser
from dataclasses import dataclass, field
from shlex import quote as sh_quote
from typing import Any, Dict, List, Pattern, Set
from urllib.parse import url... |
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Script copyright (C) Campbell J Barton
#
# 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 2
# of the License, or (at your option) any late... |
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Lookup IP address information"
class Input:
IP = "ip"
class Output:
CITY = "city"
COUNTRY = "country"
HOSTNAME = "hostname"
IP = "ip"
LOC = "loc"
ORG = "org"
POSTAL = "postal"
... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Yaoyao Liu
## Modified from: https://github.com/Sha-Lab/FEAT
## Tianjin University
## liuyaoyao@tju.edu.cn
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the r... |
import os
import sys
from pkg_resources import resource_string, resource_listdir
from walt.client.doc.markdown import MarkdownRenderer
from walt.client.doc.pager import Pager
def display_doc(topic):
try:
content = resource_string(__name__, topic + ".md").decode('utf-8')
except:
print('Sorry, n... |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verify that a target marked as 'link_dependency==1' isn't being pulled into
the 'none' target's dependency (which would otherwise lead t... |
# Copyright 2017 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.
import logging
from collections import namedtuple
from analysis import detect_regression_range
from analysis.chromecrash_parser import ChromeCrashParser
fro... |
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model
dataset_size = 1498
codes = []
path = 'encoder/rose'
for id in range(dataset_size):
code = np.loadtxt(path+'{:04d}.txt'.format(id))
codes.append(code)
#code = np.loadtxt(path+'{:04d}v.txt'.format(id))
#codes.ap... |
from typing import Any, Callable, Optional, TypeVar
import attr
from multimethod import multimethod
T = TypeVar("T")
def func_repr(func: Callable) -> str:
return func.__name__ if hasattr(func, "__name__") else "lambda"
def identity_transform(series: Any, state: dict = dict()) -> Any:
return series
def d... |
import os
import docker
class Tool:
def __init__(self, image, prefix_cmd):
self.image = image
self.prefix_cmd = prefix_cmd
self.client = docker.from_env()
self.new_cmd = []
self.volumes = None
self.container = None
def run(self, cmd, current_dir):
sel... |
from scrapy.spiders import SitemapSpider
import re
class AlzaSpider(SitemapSpider):
name = 'alza'
sitemap_urls = ['https://www.alza.cz/_sitemap-products-1.xml']
def parse(self, response):
desc = response.css('div#popis')
try:
name = desc.css('h2::text').extract_first()
... |
'''
Copyright 2013 Cosnita Radu Viorel
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribu... |
from tkinter import *
from tkinter import ttk
import socket
from threading import Thread, Lock
from queue import Queue
regs = dict()
lock = Lock()
msg_queue = Queue()
client_running = True
HOST, PORT = "localhost", 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def toggle_valv... |
"""
This program runs every image recognition test.
"""
import birdvision.quiet
import birdvision.testing
from birdvision.config import configure
def main():
configure()
birdvision.quiet.silence_tensorflow()
test_framework = birdvision.testing.run_all_tests()
test_framework.summarize_to_stdout()
if ... |
"""
this script is used for organize CUB200 dataset:
-- images
-- train
-- [:class 0]
-- [:class 1]
...
-- [:class n]
-- val
-- [:class 0]
-- [:class 1]
...
-- [:class n]
"""
import os
import PIL.Image
import numpy as np
import shutil
ori... |
__version__ = '0.0.1c'
|
# 2020.07.10
# Problem Statement:
# https://leetcode.com/problems/zigzag-conversion/
class Solution:
def convert(self, s: str, numRows: int) -> str:
# initialize answer string
answer = ""
# check empty input
if s == "":
return ""
# calculate how... |
"""Ancestry tool module."""
from mongoengine import ValidationError
from app.extensions import mongoDB
from app.tool_results.modules import SampleToolResultModule
from app.tool_results.models import ToolResult
from .constants import MODULE_NAME, KNOWN_LOCATIONS
class AncestryToolResult(ToolResult): # pylint: disa... |
from assertpy import assert_that
from common.grid import Grid
import year2020.day20.reader as reader
def test_example():
lines = ['Tile 2311:\n',
'..#\n',
'##.\n',
'#..\n',
'\n',
'Tile 1951:\n',
'#.#\n',
'#.#\n',
... |
"""initial_schema
Revision ID: 8ee4d82ef1a1
Revises: None
Create Date: 2018-08-17 12:51:06.531683
"""
# revision identifiers, used by Alembic.
revision = '8ee4d82ef1a1'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ##... |
import subprocess
import os
"""
What are the differences and similarities between ffmpeg, libav, and avconv?
https://stackoverflow.com/questions/9477115
ffmeg encoders high to lower quality
libopus > libvorbis >= libfdk_aac > aac > libmp3lame
libfdk_aac due to copyrights needs to be compiled by end user
on MacOS brew... |
def test_safe(filename, acceptable_functions=[]):
"""tests all the function calls in a file against a set of acceptable ones.
this function also does not allow importing of other modules.
returns True, [] if there are only acceptable function calls,
returns False and a list of bad function ... |
# Create dataset to load images
import torch
from torch.utils import data
from woollylib.utils.gradcam.gradcam import GradCAM
from woollylib.utils.gradcam.util import get_prediction_for_image, generate_heat_map, apply_heatmap_to_image, plot_output
def compute_gradcam(model, class_map, img, label, pred, device='cpu'... |
"""CUCM AXL Advanced APIs."""
from operator import methodcaller
from zeep.helpers import serialize_object
from .._internal_utils import flatten_signature_kwargs
from ..helpers import get_model_dict
from .base import DeviceAXLAPI
from .base import SimpleAXLAPI
class CalledPartyTracing(SimpleAXLAPI):
_factory_de... |
from enum import Enum
from time import sleep
from ctypes import CDLL, CFUNCTYPE, c_int, c_void_p, c_char_p
class Direction(Enum):
INPUT=0
OUTPUT=1
class State(Enum):
LOW = 0
HIGH= 1
lib = CDLL("libmica-gpio.so")
CMPFUNC = CFUNCTYPE(c_void_p, c_int, c_int, c_char_p)
def cb(id, state, data):
print("Input: %... |
import pandas as pd
from torch.utils.data import Dataset
class SADataset(Dataset):
def __init__(self, tokenizer, conf):
self.conf = conf
self.df = pd.read_csv(self.conf["data"]["train_path"])
self.tokenizer = tokenizer
self.data_len = self.df.shape[0]
def __getitem__(self, ite... |
import numpy as np
from scipy.stats import expon, norm, truncnorm
def dnorm(x, mean=0, sd=1, log=False):
g = norm(mean, sd)
if log:
return g.logpdf(x)
return g.pdf(x)
def pnorm(q, mean=0, sd=1, lower_tail=True, log_p=False):
if not lower_tail:
q = mean * 2 - q
g = norm(mean, sd)
... |
# Copyright (c) Facebook, Inc. and its affiliates.
import copy
from typing import Any, Dict, List, Optional, Tuple
import omegaconf
import torch
from mmf.common.registry import registry
from mmf.models.base_model import BaseModel
from mmf.modules.embeddings import (
PreExtractedEmbedding,
TextEmbedding,
T... |
"""
Copyright 2021 Dean Hall. See LICENSE for details.
The Text User Interface state machine
"""
import logging
from asciimatics.exceptions import ResizeScreenError, StopApplication
from asciimatics.scene import Scene
from asciimatics.screen import Screen
import farc
from heymac.ui import MsgsModel, RadioStngsMode... |
import itertools
import validators
from sqlalchemy import func
from sqlalchemy.orm.session import Session
from .zonerecord import ZoneRecord
from . import utils as zutils
EMSG_SESSION_TYPE_INVALID = 'Argument session must be an instance of sqlalchemy.orm.session.Session'
EMSG_MULTIVALUE_TYPE_INVALID = "Record values m... |
from collections.abc import Iterable
import numpy as np
class Individual(np.ndarray):
'''
from the numpy documentation, we subclass ndarray
to add a 'fitness' attribute
'''
__last_pop_id = 1
__default_fitness = 1e10
def __new__(cls, shape, dtype=int, buffer=None, offset=0,
strides=None, order=None... |
import unittest, silasdk
from tests.test_config import *
class Test001GetInstitutionsTest(unittest.TestCase):
def test_get_institutions(self):
payload = {
"institution_name": "1st advantage bank"
}
response = silasdk.User.get_institutions(app, payload)
self.assertTrue(r... |
##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFT... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 Cesar Sinchiguano <cesarsinchiguano@hotmail.es>
#
# Distributed under terms of the BSD license.
"""
"""
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist,Point
from nav_msgs.msg import Odometry
... |
from django.urls import path
from .views import (
indexPage,
signUpPage,
signInPage,
signOutPage,
attendeeListPage,
attendeeProfilePage,
attendeeSpeakerUpdatePage,
attendeeSpeakerViewPage,
attendeeStatsPage,
paperCreatePage,
paperRetrievePage,
paperUpdatePage,
paper... |
#!/usr/bin/env python
import rospy
import requests
from std_msgs.msg import String
import random
from geometry_msgs.msg import Twist
import os
import datetime
def talker():
initi = True
pub = rospy.Publisher('letter', String, queue_size=10)
pubPath = rospy.Publisher('folderPath', String, queue_size=900)
... |
a = "%s test %d" % ("x", 1) |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#!usr/bin/env python3
# -*- coding:utf-8 -*-
'''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
'''
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
... |
# Copyright 2021 Red Hat 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 appli... |
from rgb import DisplaySPI, color565
_DRAWLINE = const(0x21)
_DRAWRECT = const(0x22)
_FILL = const(0x26)
_PHASEPERIOD = const(0x12)
_SETCOLUMN = const(0x15)
_SETROW = const(0x75)
_CONTRASTA = const(0x81)
_CONTRASTB = const(0x82)
_CONTRASTC = const(0x83)
_MASTERCURRENT = const(0x87)
_SETREMAP = const(0xA0)
_STARTLINE ... |
"""
String methods supported by Series.
"""
import weld.encoders.numpy as wenp
import weld.grizzly.weld.str as weldstr
from weld.types import *
class StringMethods(object):
"""
String methods for Grizzly. Currently, string methods only apply to ASCII
strings; while users can pass UTF-8 strings into Griz... |
# 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 the Li... |
import click
import json
import os
import requests
import sys
import jwt
import time, sys
from prettytable import PrettyTable
from mysocketctl.ssh import SystemSSH, Paramiko
api_url = "https://api.mysocket.io/"
token_file = os.path.expanduser(os.path.join("~", ".mysocketio_token"))
# For debug
debug = False
if "MY... |
# -*- test-case-name: go.apps.http_api_nostream.tests.test_vumi_app -*-
import json
import copy
from twisted.web import resource, http, util
from twisted.web.server import NOT_DONE_YET
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue
from vumi import errors
from vumi.blinkenlights ... |
# -*- coding: utf-8 -*-
import mltk
from sklearn.covariance import EmpiricalCovariance
from mltk.data import ArraysDataStream, DataStream
import tensorkit as tk
from tensorkit import tensor as T
import sys
import torch
import numpy as np
from flow_next.common import TrainConfig, DataSetConfig, make_dataset, train_mode... |
from .single_stage import SingleStageDetector
from .search_base import SearchBaseDetector
from ..registry import DETECTORS
@DETECTORS.register_module
class TTFNeXt(SingleStageDetector, SearchBaseDetector):
def __init__(self,
backbone,
neck,
bbox_head,
... |
from api.core import requests
from api.conf.settings import env, HAWK_LITE_PERFORMANCE_CREDENTIALS
def get(appended_address, headers=None):
url = _build_absolute_uri(appended_address).replace(" ", "%20")
return requests.get(url, headers=headers, hawk_credentials=HAWK_LITE_PERFORMANCE_CREDENTIALS)
def post(... |
from typing import Any, List, Dict, Type
class DataType:
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DataType):
return False
return self.__dict__ == other.__dict__
class Unsupported:
def __new__(cls, *args, **kwargs):
# Can't raise NotImplemen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.