content stringlengths 5 1.05M |
|---|
from pudzu.charts import *
from glob import glob
df = pd.read_csv("datasets/flagsbiband.csv").set_index("colours")
FONT, SIZE = sans, 24
fg, bg = "black", "#EEEEEE"
default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a476b06333d9fe9960572b66b9.jpg"
COLORS = { "W": "white", "Y": "yellow", "R": "red... |
# coding=utf-8
import copy
import Putil.demo.deep_learning.base.base_operation as standard
import util.base_operation as project
def checkpoint_factory(args):
temp_args = copy.deepcopy(args)
def generate_checkpoint_func():
if temp_args.framework == 'torch':
return standard.torch_checkpoint... |
from yandex_translate import YandexTranslate
from pycountry import languages
from utils.text import detect_language
from .baseprovider import BaseProvider
class TranslateProvider(BaseProvider):
@staticmethod
def get(query, config, params={}, lang='en'):
translator = YandexTranslate(key=config['yandex_... |
from collections import OrderedDict
from . import regexshim as _re
import sys
""" tags which we consider empty. This is largely the same as HTML but includes a few more. """
_EMPTY_TAGS = ( 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img',
'input', 'keygen', 'link', 'meta', 'param', 'sour... |
# Autogenerated file. ANY CHANGES WILL BE OVERWRITTEN
from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
EventData, \
CompoundEventData
DUMP_PARTIAL = [
CompoundEventData(
serv... |
from flask import Flask, render_template
from zcmeasure import get_sensor_data
from zcmeasure_ui.utils import get_local_ip
app = Flask(__name__)
@app.route("/")
def home():
return render_template('index.html', LOCAL_IP=get_local_ip())
@app.route("/measure", methods=['GET'])
def get_measure():
data = get_se... |
from django.db import models
class Job(models.Model):
title = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: yandex/cloud/ai/vision/v2/image_classifier.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection... |
"""
test_survey_confs.py
"""
import sys
import os
import pytest
import shutil
# define location of input files for testing
mydir = os.path.dirname(os.path.abspath(__file__))
# import functions to aid testing
sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers'))
from helper import *
from quanformer.surv... |
import pkg_resources
import re
from convokit.model import Corpus, User, Utterance
from collections import defaultdict
from typing import Callable, Tuple, List, Dict, Optional, Collection, Hashable, Union
CoordinationWordCategories = ["article", "auxverb", "conj", "adverb",
"ppron", "ipron... |
import setuptools
import shrub
setuptools.setup(
name=shrub.NAME,
version=shrub.VERSION,
description=shrub.DESCRIPTION,
packages=setuptools.find_packages(),
python_requires='>=3.5.*, <4',
author='王振华(Zhenhua WANG)',
author_email='i@jackwish.net',
url="https://jackwish.net/shrub",
... |
import boto3
import datetime
import uuid
import os
import urllib
from django.http import JsonResponse
def sign_s3(request):
print(request);
S3_BUCKET = os.environ.get('S3_BUCKET')
today = datetime.datetime.now()
date_path = today.strftime("%Y/%m/%d")
file_uuid = str(uuid.uuid4().hex)
file_name... |
# Copyright (C) 2020-Present the hyssop authors and contributors.
#
# This module is part of hyssop and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
File created: August 21st 2020
Modified By: hsky77
Last Updated: November 21st 2020 21:35:38 pm
'''
from typing import Di... |
from barry.datasets.dataset import Dataset
from barry.datasets.dataset_power_spectrum_abc import PowerSpectrum
from barry.datasets.dataset_correlation_function_abc import CorrelationFunction
from tests.utils import get_concrete
class TestDataset:
classes = get_concrete(Dataset)
concrete = []
@classmethod... |
from .JavaMethod import JavaMethod
class JavaClass:
def __init__(self, name=""):
self.name = name
self.inherited_class_name = ""
self.access_level = ""
self.package = ""
self.imports = []
self.methods = []
def add_method(self, method: JavaMethod):
self.methods.append(method)
def add_import(self, t... |
import geopandas as gpd
import pandas as pd
import numpy as np
import glob
import zipfile
import os
import xarray as xr
import json
from shapely.geometry import Polygon
import csv
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
hruid = 'nhru_v11' # for GFv11_v2e
gfs_file = Path('HRU_M... |
def test_stress_strain_curve():
"""
-Check stress_strain_curve.py to see if it correctly copies and converts the data (into pif and panda)
-Check to see if it correctly cuts off the bad end of data
-Check to see if it correctly reverses data when in compression
TBW
:return:
"""
pass
|
# -*- coding: utf-8 -*-
#**********************************************************
#* CATEGORY JARVIS HOME AUTOMTION
#* GROUP SPEECH TO TEXT
#* AUTHOR LANCE HAYNIE <LANCE@HAYNIEMAIL.COM>
#**********************************************************
#Jarvis Home Automation
#Copyright (C) 2017 Haynie Resear... |
from dataclasses import dataclass
from logging import Logger
import re
from typing import List, Pattern
from src.helpers import Helpers
from src.modules.store import Store
@dataclass
class CustomRule:
"""Dataclass for custom rules."""
name: str
action: str
pattern: Pattern
class Filter:
"""Cla... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import cv2
img = cv2.imread('C:/Users/hp/Desktop/ml/Pikachu/a.jpg', cv2.IMREAD_UNCHANGED)
print('Original Dimensions : ',img.shape)
scale_percent = 60 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height =... |
import numpy as np
import pandas as pd
import pandas._testing as tm
class TestIndexingCallable:
def test_frame_loc_callable(self):
# GH 11485
df = pd.DataFrame({"A": [1, 2, 3, 4], "B": list("aabb"), "C": [1, 2, 3, 4]})
# iloc cannot use boolean Series (see GH3635)
# return bool i... |
"""Solutions to Paths chapter."""
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import seaborn as sns
from nams.functions import render_html
def bfs_algorithm():
"""
How to design a BFS algorithm.
"""
ans = """
How does the breadth-first search work?
It essentially is as f... |
from pathlib import Path
import toml
from semantic_version import Version
def get_version() -> Version:
"""
Returns the version of Archimedes.
"""
main_path = Path(__file__).resolve().parents[2] # /archimedes/
# Note this depends on where this module is located within Archimedes
pyproject ... |
# Fill in this file with the code to get room details from the Webex Teams exercise
|
"""Use case for automating the ingestion of CVE reports"""
import glob
import os
import sys
import time
from getpass import getpass
from io import FileIO
import requests
def upload_cve(file: FileIO) -> dict:
""" Uploads vulnerability list to Automox Vulnerability Sync endpoint.
Args:
file (FileIO): ... |
import uuid
from datetime import timedelta
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Notification(models.Model ):
"""
Model that represents an video.
"""
emai... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 16:42:32 2020
@author: admin
"""
import numpy as np
class AverageLoss(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def upd... |
###############################
# python imports
###############################
import socket
from time import sleep, time
from threading import Thread
from typing import Tuple
import traceback
from pyacyclicnet.core.types.request import Request
###############################
# global imports
#####################... |
#!/usr/bin/python3
from freebox_crystal import deamon
ip='localhost'
api_key='***'
out_sensors = {'Switch': 529, 'WAN': 530}
in_sensors = {'WAN': 528}
domoticz_processor = deamon.DomoticzProcessor('http://'+ip+':8080', api_key, out_sensor_dict=out_sensors,
in_sensor_dic... |
OCTICON_HUBOT = """
<svg class="octicon octicon-hubot" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M0 8a8 8 0 1116 0v5.25a.75.75 0 01-1.5 0V8a6.5 6.5 0 10-13 0v5.25a.75.75 0 01-1.5 0V8zm5.5 4.25a.75.75 0 01.75-.75h3.5a.75.75 0 010 1.5h-3.5a.75.75 0 01-.75-... |
from homeassistant.const import (
LENGTH_KILOMETERS)
MERCEDESME_COMPONENTS = [
"sensor",
"lock",
"binary_sensor",
"device_tracker",
"switch"
]
BINARY_SENSORS = {
"liquidRangeCritical": ["Liquid Range Critical",
None,
"binarysensors",... |
"""
emby eac3 episode locator
"""
import os
import sys
import time
import subprocess
import logging
import shutil
import requests
_LOGGER = logging.getLogger(__name__)
logging.basicConfig(filename='/config/embyac3.log', filemode='a', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%... |
###############################################################################
#
# seqUtils.py - Common functions for interacting with sequences
#
###############################################################################
# #
# T... |
import logging
import re
import discord
from discord.ext import commands
from typing import Optional, Union
import utils
from db_classes.PGAutoreactDB import PGAutoreactDB
logger = logging.getLogger("Referee")
from Referee import can_ban, can_kick
class Autoreactions(commands.Cog):
def __init__(self, bot: co... |
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... |
import re
import functools
from pyats.topology import Link as ATSLink
from genie.utils.cisco_collections import OrderedSet
class Link(ATSLink):
@classmethod
def validate_name(cls, name):
if re.match(r'^(?:L\d+)$', name):
return name
raise ValueError('Not a valid %s name: %r'
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from modules.logging import logging_decorator
from telegram.ext.dispatcher import run_async
from telegram import ChatAction
from telegram.ext import MessageHandler, PrefixHandler
from modules.utils import Caption_Filter, send_image
from PIL import Image, ImageDraw, ImageOps
fro... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 15 20:18:07 2014
@author: leo
"""
import matplotlib.pyplot as plt
import numpy as np
#Define time
t = np.arange(-50,50,.1,dtype=np.float64)
#Define functions
ut = lambda t: 1 if t >= 0 else 0
xt = lambda t: 2*t*np.sin(3*t - 2)*ut(t)
#Define signals
x1 = [xt(a) for a i... |
from django.urls import path
from . import views
app_name = 'recsys'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('<int:book_id>/', views.book.as_view(), name='book'),
path('search/', views.SearchResultsView.as_view(), name='search_results'),
path('ratings/', views.RatingsView... |
from datetime import datetime
from init import db
class ContactMessage(db.Model):
__tablename__ = "contact"
id = db.Column(db.Integer, primary_key=True)
created_date = db.Column(db.DateTime, default=datetime.now())
name = db.Column(db.String(100))
email = db.Column(db.String(100))
message = ... |
class DeclineNoun:
def __init__(self,nom,gen,gender,irregular=False):
self.nom = nom
self.gen = gen
self.gender = gender
self.irregular = irregular
def id_declension(self):
if self.gen[-2:] == "ae":
return [1, self.gen[:-2]]
elif self.gen[-2:] == "is... |
#
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# 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,... |
"""pronto_utils.py"""
import wget
import os
import zipfile
import pandas as pd
import matplotlib.pyplot as plt
import seaborn; seaborn.set() # for plot stylings
def download_if_needed(URL, filename):
"""
Download from URL to filename unless filename already exists
"""
if os.path.exists(filename):
... |
#!/usr/bin/env python3
# Copyright 2016 UCSC Computational Genomics Lab
# Original contributor: Arjun Arkal Rao
#
# 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/li... |
from unittest import TestCase
from prometheus_client.registry import CollectorRegistry
from app.prom.metrics.general.resource import Resource, NAME, CURRENT_UTILIZATION, LIMIT_VALUE
from tests.helpers import setUpApp, with_context
class TestResource(TestCase):
def setUp(self):
setUpApp(self)
@with... |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
from KratosMultiphysics import *
def ConstructPreconditioner(configuration):
if hasattr(configuration, 'preconditioner_type'):
preconditioner_type = configuration.precondi... |
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
mem = {}
ans = []
for i in nums : mem[i] = True
for i in range(1,len(nums)+1):
if i not in mem : ans.append(i)
return ans |
from math import *
import math
import sys
import random
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
# xMin, xMax, yMin, yMax = map(int, input().split())
x_min, x_max, y_min, y_max = -100,100,-100,100
xAxisLimits = [x_min-200, x_max+200]
yAxisLimits = [y_min-200, y_max+200]... |
from PIL import Image
import numpy as np
import openpyxl
from openpyxl.styles import PatternFill
from openpyxl.styles.borders import Border, Side
from openpyxl.utils import get_column_letter
import math
import pandas as pd
from sklearn.cluster import KMeans
import colorsys
import sys
def trimmingImg(im=[[[0,0,0]]]):
... |
#coding:utf-8
import json
import socket
import time
from zk import *
from util import *
import subprocess
import psutil
import os
import re
class Agent:
def __init__(self, zk, host, task_id, agent_id):
self.zk = zk
self.host = host
self.task_id = task_id
self.agent_id = agent_id
... |
# Jacob Christensen
# CS 3270
#Imports
import sqlite3
import os
import sys
#Constants
#Variables
#Functions
def dbg(database): #DEBUG see what's actually in the database
result = database.cursor().execute('SELECT * FROM files')
for row in result:
print row
#Classes
#==MAIN==
if len(sys.argv) != 3:
print 'Usa... |
"""Support for Sinch notifications."""
import logging
from clx.xms.api import MtBatchTextSmsResult
from clx.xms.client import Client
from clx.xms.exceptions import (
ErrorResponseException,
NotFoundException,
UnauthorizedException,
UnexpectedResponseException,
)
import voluptuous as vol
from openpeerp... |
# -*- coding: utf-8 -*-
VERSION = (0, 0, 8)
def get_version():
"""Returns project version in a human readable form."""
version = '.'.join(str(v) for v in VERSION[:3])
sub = ''.join(str(v) for v in VERSION[3:])
return version + sub
|
import glob
import logging
import os
import struct
import threading
import cv2
import numpy as np
from .data_models.converter import get_mat_from_ocvmat
from .fsb_queue import FsbQueueConsumer
from .utils import get_folder, get_session_folder
LOGGER = logging.getLogger("consumer")
class Consumer(threading.Thread):... |
#!/usr/bin/python
# Code modified by: Nitin J. Sanket, PhD in Computer Science Student,
# University of Maryland, College Park
# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
#
# This example program shows how to find frontal human faces in an image and
# estimate their ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if None in [root.left, root.right]:
... |
import numpy as np
from mpi4py import MPI
from parla.array import copy
from parla.cuda import gpu
from parla.cpu import cpu
from parla.ldevice import LDeviceSequenceBlocked
from parla.tasks import *
import time
def main():
comm = MPI.COMM_WORLD
print(comm.Get_rank(), comm.Get_size())
a = np.random.rand... |
import os,sys
import webbrowser
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.cm as cm
import matplotlib.pylab as plt
from matplotlib.colors import LinearSegmentedColormap
plt.rcParams['font.family'] = 'monospace'
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
Z = np.loadtx... |
import setuptools
setuptools.setup(
name='ucbhr',
version='0.1',
description='Query the UC Berkeley HRMS.',
url='https://github.com/ryanlovett/ucbhr',
author='Ryan Lovett',
author_email='rylo@berkeley.edu',
packages=setuptools.find_packages(),
install_requires=[
'aiohttp'
],
entry_points={
'con... |
#!/usr/bin/env python3
from fruit.banana.chocolate import Chocolate
c = Chocolate()
c.do_something() |
import glob
import json
import re
patients = glob.glob("./Patient*")
#patients = sorted(glob.glob("./Patient*"))
types = ["AllergyIntolerance", "Condition", "Encounter", "MedicationPrescription", "DiagnosticReport", "Immunization", "Observation"]
resources = []
def add_resource(rid, r):
r['id'] = rid
resourc... |
__all__ = ('AudioSource', 'DownloadError', 'LocalAudio', 'YTAudio')
import os, shlex, subprocess
from pathlib import Path
from scarletio import CancelledError, Task, alchemy_incendiary
from ..core import KOKORO
from .opus import FRAME_LENGTH, FRAME_SIZE
PLAYER_DELAY = FRAME_LENGTH / 1000.0
del FRAME_LENGTH
DEFA... |
from test_plus.test import TestCase
from .models import Location
from django.contrib.gis.geos import Point
# Tests for geodata classes
class LocationModelTest(TestCase):
def test_saving_and_retrieving_locations(self):
first_point = Location()
first_point.name = "The first point"
first_poi... |
import pyspark
spark = pyspark.sql.SparkSession.builder.appName("pyspark-notebook") \
.master("spark://spark-master:7077") \
.config("spark.jars.packages", "io.delta:delta-core_2.12:0.8.0") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_c... |
# Generated by Django 3.1.12 on 2021-07-19 20:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calc', '0036_auto_20210719_2046'),
]
operations = [
migrations.AlterField(
model_name='adding',
name='num1',
... |
from torch.utils.data import ConcatDataset
import numpy as np
from ssd.config.path_catlog import DatasetCatalog
from .waymo import WaymoDataset
from .tdt4265 import TDT4265Dataset
_DATASETS = {
'WaymoDataset': WaymoDataset,
'TDT4265Dataset': TDT4265Dataset
}
def build_dataset(base_path: str, dataset_list, tr... |
"""
- Command line tests:
- pixis
- pixis -b buildfiles/build1.py
- pixis --build buildfiles/build1.py
- pixis -o OUTPUT
- pixis --output OUTPUT
- pixis -t mytemplates
- pixis --templates mytemplates
"""
def test_base_command():
pass
def test_option_build():
pass
def test_optio... |
# Copyright 2016 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 page_sets import page_cycler_story
from telemetry import story
from telemetry.page import cache_temperature as cache_temperature_module
cache_temperatu... |
from .io import read_jsonl, write_jsonl
from .s3_policy_data import PolicyDocumentsDownloader
__all__ = ['read_jsonl', 'write_jsonl', 'PolicyDocumentsDownloader']
|
import sys
import obspy
import os
import time
import numpy as np
import pandas as pd
from mpi4py import MPI
from seisgo.utils import split_datetimestr
from seisgo import downloaders
#########################################################
################ PARAMETER SECTION ######################
######################... |
from flask_restful import fields
"""Defining how resources are represented
"""
company_serializer = {"companyID": fields.Integer,
"tenderID": fields.Integer,
"companyName": fields.String,
"companyRegistrationNo": fields.String,
"d... |
import numpy as np
import sys
from schools3.config import base_config
from schools3.data.features.processors.impute_null_processor import ImputeBy
config= base_config.Config()
config.fill_values ={
'absence_rate': ImputeBy.MEAN,
'unexcused_absence_rate': ImputeBy.MEAN,
'absence_rate_perc': ImputeBy.MEAN
}... |
import os
from typing import TYPE_CHECKING
from blinker import signal
from pluginbase import PluginBase
if TYPE_CHECKING:
from scronsole.widgets.main_screen import MainScreen
plugin_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
signal_pre_process_message = signal('pre_process_message... |
import os
import suds.client
from .models import BankTransaction
from datetime import datetime
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http import HttpResponseRedirect
import time,binascii,random
import payment.views
from payment.models import BankP... |
# https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytorch/lovasz_losses.py
#
# Lovasz-Softmax and Jaccard hinge loss in PyTorch
# Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License)
from lib.include import *
# Computes gradient of the Lovasz extension w.r.t sorted errors
# See Alg. 1 in paper
def compute_l... |
import functools
import torch.utils.model_zoo as model_zoo
from .resnet import resnet_encoders
from .dpn import dpn_encoders
from .vgg import vgg_encoders
from .senet import senet_encoders
from .densenet import densenet_encoders
from .inceptionresnetv2 import inceptionresnetv2_encoders
from .inceptionv4 import incepti... |
#! /usr/bin/env python
# attempt 1
def find_distance(a, b, c):
"""Determine if distance between three ints is equal
assuming unsorted entries"""
int_holder = [a, b, c]
int_holder.sort()
distance_1 = int_holder[1] - int_holder[0]
distance_2 = int_holder[2] - int_holder[1]
if distance_1 ==... |
import os.path
import frappe
from frappe import _
import datefinder
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import pickle
from datetime import datetime, timedelta
class CalendarEvent:
# Creates required directories to store authorization credentials for ... |
# gp_signals.py
"""Contains class factories for Gaussian Process (GP) signals.
GP signals are defined as the class of signals that have a basis
function matrix and basis prior vector..
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import math
import i... |
# -*- coding: utf-8 -*-
import logging
import mapping_career_causeways
import mapping_career_causeways.load_data_utils as load_data
import pandas as pd
import pickle
data = load_data.Data()
data_path = f'{mapping_career_causeways.Paths().data_dir}'
logger = logging.getLogger(__name__)
def main():
"""
Runs da... |
from __future__ import absolute_import
from distutils.core import setup
from setuptools import find_packages
import versioneer
setup(
name="custom_inherit",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
package_dir={"": "src"},
packages=find_packages(where="src", exclude=["t... |
from flask import Blueprint
tags = Blueprint("tags", __name__)
from . import routes
|
import os
class GraphError(Exception):
pass
class Graph:
"""
A dependency graph of the targets in the build script.
"""
def __init__(self):
self._targets = dict()
self._deps = dict()
self._dag = dict()
def register_target(self, callable, name):
self._targets[n... |
def load_config(config_data):
if 'gcsfs' not in config_data:
raise Exception("gcsfs section is mandatory in the configuration")
required_parameters = ('project_id',)
if set(required_parameters) <= set(config_data['gcsfs']):
pass
else:
raise Exception('You must provide {} to acc... |
"""A package of Python modules, used to configure and test IBIS-AMI models."""
print("pyibisami is a package of sub-modules, and is not directly executable.")
print("Perhaps, you meant:")
print(" - pyibisami.ami_config")
print(" - pyibisami.run_tests")
raise RuntimeError("pyibisami not executable.")
|
__author__ = 'ah14aeb'
from configobj import ConfigObj, ConfigObjError
import argparse
def get_config(argv):
parser = argparse.ArgumentParser()
parser.add_argument("config_file", help="the config file path")
parser.add_argument("-f", "--testname", help="used as the output foldername")
parser.... |
""" indy-agent python implementation
"""
import asyncio
import os
import json
from indy import wallet, did, crypto
from router import Router
from transport.http_transport import HTTPTransport
from serializer import JSONSerializer as Serializer
from config import Config
# Module Routes
from modules.testing import reg... |
#! /usr/bin/env python3
## -*- coding: utf-8 -*-
from __future__ import print_function
from triton import *
import random
import string
import sys
import lief
import os
DEBUG = False
# DEBUG = True
TARGET = os.path.join(os.path.dirname(__file__), './bin/crypto_test-thumb-Os.bin')
STOP_ADDR = None
MAX_INSTRS =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from utility.common import Common
from utility.package import Package
if __name__ == "__main__":
files = ['sync.py']
directory = Common.get_cmd_dir()
paths = [Common.join_paths(directory, x) for x in files]
distdir = Common.get_cmd_dir()
Package(paths... |
#!/usr/bin/env python
'''
Evaluate the values of density, exchange-correlation functional and XC
potential on given grid coordinates.
'''
import numpy
from pyscf import gto, dft, lib
from pyscf.dft import numint
from pyscf.dft import r_numint
mol = gto.M(
verbose = 0,
atom = '''
o 0 0. 0.
... |
# -*- coding: utf-8 -*-
"""
Simple demo using kernel activation functions with convolutional networks on the MNIST dataset.
"""
# Keras imports
from keras import datasets
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
from keras.utils import to_categorical
import ker... |
import numpy as np
class AbstractDataModel(object):
def __init__(self):
pass
def sample_joint_data_points(self, n):
"""
:return: x, t, y, y_cf, z, sigma
where - t is assumed to be an element of range(0, num_treatments)
- y_cf is assumed to be a list of le... |
#
# Copyright 2019 Quantopian, 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 wr... |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import pygame,random
import sys
import time
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("words testing")
enfont = pygame.font.Font(None, 60)
zhfont = pygame.font.Font('simhei.ttf', 25)
xiang = pygame.im... |
import torch
import torch.nn as nn
def smape(yhat, y):
return torch.abs(yhat - y) / (torch.abs(yhat) + torch.abs(y)) / 2 |
#===============================================================================
# Copyright 2021 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.o... |
import torch
import time
import random
import socket
import argparse
from model import ServerSegment, PartySegment
from bank_dataset import BankDataset
from util import data_loader, recv_msg, send_msg, agg_tensor
from plot import plot_train
def get_args():
parser = argparse.ArgumentParser()
parser.add_argumen... |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... |
import io
import tempfile
from zipfile import ZIP_DEFLATED, ZipFile
from aiida.orm import Data
from aiida_lammps.common.parse_trajectory import (
create_structure,
iter_trajectories,
parse_step,
)
class LammpsTrajectory(Data):
"""Store a lammps trajectory file.
Each trajectory step is stored as... |
import sys
import os
import nose
import unittest
import mox
import json
import sqlalchemy
from nose.plugins.attrib import attr
from nose import with_setup
from heat.tests.v1_1 import fakes
from heat.engine import instance as instances
from heat.engine import volume as volumes
from heat.engine import manager as manag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.