content stringlengths 5 1.05M |
|---|
def test_eth_blockNumber(rpc_client):
result = rpc_client('eth_blockNumber')
assert result == 0
|
import unittest
from appium import webdriver
from config.context import Context
from libs.finder import By
from libs.pageutil import AndroidPageUtil, IOSPageUtil
class AndroidBaseTest(unittest.TestCase):
def setUp(self):
desired_caps = {}
android_config = Context.get_instance().get_android_desi... |
#!/usr/bin/env python
"""
__ __ __
.----.-----.---.-.-----| |_.-----.----.--------.-----| | |_
| __| _ | _ |__ --| _| -__| _| | -__| | _|
|____|_____|___._|_____|____|_____|__| |__|__|__|_____|__|____|
--IPython Shell for Interactive Explor... |
from .auth import auth_api as Authentication
from .notes import notes_api as Notes
from .export import export_api as Export |
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import time
import unittest
import uuid
from hfc.fabric.client import Client
from hfc.fabric.user import create_user
from test.integration.config import E2E_CONFIG
class BaseTestCase(unittest.TestCase):
"""
Base class for test cases.
All ... |
# -*- coding: utf-8 -*-
"""Class for the ogs KINETRIC REACTION file."""
from ogs5py.fileclasses.base import BlockFile
class KRC(BlockFile):
"""
Class for the ogs KINETRIC REACTION file.
Parameters
----------
task_root : str, optional
Path to the destiny model folder.
Default: cwd+... |
"""
LeetCode Problem 122. Best Time to Buy and Sell Stock II
Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Written by: Mostofa Adib Shakib
Language: Python
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2: return 0 # special case
... |
# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml.
from gridcapacity.models import NodeRegistration
from flask import request, jsonify
from io import StringIO
def ListCapacityHandler():
nodes = []
country = request.values.get('country')
mru = request.values.get('mru')
cru... |
import numpy as np
import simtk.unit as unit
def get_n_lipids_from_size(total_area = 10000 * unit.angstroms**2, p_POPC = 0.5 , p_DPPC = 0.3, p_DOPC = 0.2):
area_POPC = (4 / np.pi)* 68.3 * unit.angstroms**2
area_DPPC = (4 / np.pi)* 63 * unit.angstroms**2
area_DOPC = (4 / np.pi)* 69.7 * unit.angstroms**2
... |
# xpyBuild - eXtensible Python-based Build System
#
# Copyright (c) 2013 - 2018 Software AG, Darmstadt, Germany and/or its licensors
# Copyright (c) 2013 - 2018 Ben Spiller and Matthew Johnson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-02 01:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_remove_null_urls'),
]
operations = [
migrations.AlterField(
model_name='experiment',
... |
def is_iree_enabled():
try:
import iree.runtime
import iree.compiler
except:
return False
return True
|
#!/usr/bin/env python3
"""
Geoscience Australia - Python Geodesy Package
Constants Module
"""
from math import sqrt
from datetime import date
c_vac = 299792.458
k_0 = 0.9996
# Ellipsoid Constants
class Ellipsoid(object):
def __init__(self, semimaj, inversef):
self.semimaj = semimaj
self.inverse... |
#!/usr/bin/env python3
import os
import sys
def main ():
NAMES = sys.argv [1:]
if len (NAMES) == 0:
script=os.path.basename(sys.argv[0])
print('Usage: {} NAME [NAME2 ...]'.format(script))
sys.exit(1)
if len (NAMES) == 1:
print ('Hello to the 1 of you: ' + NAMES[0] + '!')
if len (NAMES) == 2:
print ('... |
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class EntropyCoder(object):
def __init__(self, entropy_coder_precision=16):
super().__init__()
from .MLCodec_rans import RansEncoder, RansDecoder
self.encoder = RansEncoder()
self.decoder = RansDecoder(... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from pathlib import Path
datadir = Path(__file__).parent / 'cardanopy' / 'data'
files = ['data/' + str(p.relative_to(datadir)) for p in datadir.rglob('*')]
setup(name='cardanopy',
version='0.1.10-dev1',
description='Cardano CLI tools for p... |
import codecs
import time
import geopy.geocoders
import unicodecsv
from django.core.management import BaseCommand, CommandError
from django.db import transaction
from django.template import Context, Template, TemplateSyntaxError
from django.utils.encoding import force_text
from geopy import get_geocoder_for_service
fr... |
# -*- coding: utf-8 -*-
"""Test that models can be executed."""
import importlib
import os
import unittest
from typing import Any, MutableMapping, Optional
import numpy
import torch
import unittest_templates
import pykeen.experiments
import pykeen.models
from pykeen.models import (
ERModel, EntityEmbeddingModel... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from conda.exports import text_type
from contextlib import contextmanager
from logging import getLogger, Handler
from os.path import exists, join
from shlex import split
from shutil import rmtree
from tempfile import mkdtemp
from ... |
# String Format
# As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
'''
age = 23
txt = "My name is Nayan, I am " + age + "Years old"
print(txt) #Error
'''
# But we can combine strings and numbers by using the format() method!
# The format() method takes the passed arg... |
# Copyright 2019-present Kensho Technologies, LLC.
from itertools import chain
from graphql.type import GraphQLSchema
from ...schema import (
FilterDirective,
FoldDirective,
MacroEdgeDefinitionDirective,
MacroEdgeDirective,
MacroEdgeTargetDirective,
OptionalDirective,
RecurseDirective,
... |
"""
Blueprint module for accessing request states and results
"""
import logging
from flask import abort, Blueprint, jsonify, url_for
log = logging.getLogger(__name__)
USE_EXTERNAL_URLS = True
def get_state_response(ticket_id: str):
"""
Creates a response containing a valid url for the state of the request... |
import sys
DESTINATIONS = {
'': '000',
'M': '001',
'D': '010',
'MD': '011',
'A': '100',
'AM': '101',
'AD': '110',
'AMD': '111'
}
JUMPTARGETS = {
'': '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '1... |
#! /usr/bin/env python
# title : SisoDecoder.py
# description : This class implements soft input soft output decoder for specified trellis.
# Its input is a trellis instance. The max-log-BCJR algorithm is employed.
# author : Felix Arnold
# python_version : 3.5.2
class SisoDe... |
# TODO
#
# @author Oktay Acikalin <oktay.acikalin@gmail.com>
# @copyright Oktay Acikalin
# @license MIT (LICENSE.txt)
# TODO make use of http://docs.python.org/library/itertools.html
from inspect import getargspec
from diamond.helper.weak_ref import Wrapper
# from diamond.decorators import time, dump_args
list... |
def annual_query(df):
return df["subscription.plan.interval"] == 'year'
def time_range_query(df,start_time,end_time):
return ((df.created >= start_time) & (df.created < end_time)) & (df.amount_due > 0) # TODO - move amount due to separate filter
def billing_status_query(df):
return (df.status != 'draft') &... |
import copy
import torch
from pathlib import Path
import numpy as np
from metrics import *
from utils import get_predictions
def test(model_best, model_last, device, test_set_generator, wandb, multiclass_labels):
model_best.eval()
model_last.eval()
print("")
print("########################")
print... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Description
"""
import torch
from ptranking.metric.adhoc_metric import torch_ideal_dcg
from ptranking.ltr_global import global_gpu as gpu, tensor
#######
# For Delta Metrics
#######
def get_delta_ndcg(batch_stds, batch_stds_sorted_via_preds, multi_level_rele=True)... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 28 13:13:37 2014
@author: eladn
"""
import logging
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import savemat
from component_contribution.thermodynamic_constants import R, default_c_range, default_c_mid
from component_contribution.component_contribut... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 1 23:58:42 2018
Snake Mini project Starter Code
Name: Tomer Ferdman
Date: 08/07/2018
"""
import turtle
import random # We'll need this later in the lab
import time
turtle.tracer(1,0) # This helps the turtle move more smoothly
SIZE_A = 1000
SIZE_B = 1000
SIZE_X=550
SIZE_Y... |
#!flask/bin/python
#==============================================================================#
# --- globo-fan-remote --- #
# author: Max Stark #
# date: March 2018 ... |
import torch
use_cuda = torch.cuda.is_available()
def check_nan(model):
for name, param in model.named_parameters():
if torch.isnan(param).any():
return False
return True
def evaluate(model, criterion, dataloader):
"""evaluate auto-encoder"""
model.eval() # change BN
loss = 0.... |
import torch.nn as nn
import torch.nn.functional as F
"""
MLP Layer used after graph vector representation
"""
class MLPReadout(nn.Module):
def __init__(self, input_dim, output_dim, L=2): # L=nb_hidden_layers
super().__init__()
list_FC_layers = [
nn.Linear(input_dim // 2**l, inpu... |
from django.db import models
from rest_framework import serializers
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin, ListBulkCreateUpdateAPIView
class Foo(models.Model):
name = models.CharField(max_length=20)
class Meta:
app_label = "foobar"
class FooSerializer(BulkSerialize... |
from matplotlib.font_manager import FontProperties
# Attributes on FontProperties object to check for consistency
keys = [
"get_family",
"get_style",
"get_variant",
"get_weight",
"get_size",
]
def test_fontconfig_pattern():
"""Test converting a FontProperties to string then back."""
... |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import time
from tempfile import gettempdir
# pylint: disable=import-error
from hyperopt import trials_from_docs
from openvino.tools.pot.benchmark.benchmark import benchmark_embedded
from openvino.tools.pot.graph import save_model
from... |
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
... |
from gym.envs.registration import register
register(
id='warehouse-v0',
entry_point='gym_wahrehouse.envs:WareHouse',
)
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="Medeina",
version="1.6",
author="Daniel Davies",
author_email="dd16785@bristol.ac.uk",
description="A cumulative food web",
long_description="hello",
long_description_content_type=... |
#!/usr/bin/env python
import pdb
import argparse
from brick_server import create_app
def get_args():
argparser = argparse.ArgumentParser()
argparser.add_argument('--configfile',
help='Location of the config file',
type=str,
def... |
import os
import uuid
import wandb
import logging
from tensorboardX import SummaryWriter
class Base:
"""
Base configure file, which contains the basic training parameters and should be inherited by other attribute configure file.
"""
def __init__(self, config_name, work_dir):
self.... |
import os
from config import paths
from utils import generic
def screen(fasta_path=None, output_path=None):
if not fasta_path:
fasta_fname = "mg_50.fasta"
fasta_path = os.path.join(paths.ROOT, 'data', 'user', 'input', fasta_fname)
output = []
alphabets = set(generic.AA3_to_AA1.values())
... |
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name = 'csvTovcf',
packages = ['csv2vcard'],
version = '0.3.0',
description = 'A library for converting csv to .vcf file',
long_description = README,
long_des... |
#-------------------------------------------------------------------------------
# Name: moidfy_annotation_path
# Purpose: strips old path from the annotaion
# Environment: Windows 10 OS, Python 3.6
# Author: No This Is Patrick
#
# Created: 17/02/2018
# Modify XML File Library: https://docs.p... |
import json
import os
from appdirs import user_config_dir
def merge_config_dicts(base_config, merge_src):
result = {}
for key in merge_src:
if key in base_config:
if isinstance(base_config[key], dict) and isinstance(merge_src[key], dict):
result[key] = merge_config_dicts(base_config[key], merge_s... |
from enum import Enum, unique
from math import fabs
import random
from tetris_engine import TetrisEngine, Playfield, TetrominoShape
"""
TODO if we record how the agent performs we can use emojis
🡲 Wide-Headed Rightwards Medium Barb Arrow
🡰 Wide-Headed Leftwards Medium Barb Arrow
🡳 Wide-Headed Downwards Medium Barb... |
from typing import *
from faker.providers import BaseProvider
from .models import Player, ScoreStats, Score, Characteristic, Difficulty, Badge
class ScoreSaberProvider(BaseProvider):
def role(self) -> Optional[str]:
roles = [
"Owner", "Nomination Assessment Team", "Ranking Team", "Quality As... |
import socket
from threading import Thread
class TcpSock(object):
def __init__(self,host="127.0.0.1",port=9999, responder = None ):
self.host = host
self.port = port
self.bufsize = 128
self.sock = None
self.socketThread = None
self.responder = responder
def _co... |
import os
import numpy as np
import json
from PIL import Image
from model import *
import matplotlib.pyplot as plt
import matplotlib.patches as patches
data_path = '../data/RedLights2011_Medium'
preds_path = '../data/hw01_preds'
kernels = buildKernels()
good_examples = ['RL-011.jpg', 'RL-019.jpg', 'RL-021.jpg', 'RL-... |
from itertools import product
from functools import reduce
from operator import getitem
import random
from uuid import uuid4
from joblib import Parallel, delayed
import numpy as np
class GridParallel(object):
def __init__(self, *args, **kwargs):
"""Wrapper for joblib.Parallel for computing the same func... |
#!/usr/bin/python
# Classification (U)
"""Program: main.py
Description: Integration testing of main in rmq_2_sysmon.py.
Usage:
test/integration/rmq_2_sysmon/main.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unit... |
from __future__ import print_function
import heapq
import itertools
import copy
import codecs, sys
stdout = codecs.getwriter('utf-8')(sys.stdout)
def forward_dp(dictionary, graph):
graph.nodes_list[0][0].f = 0
for i in range(1, graph.x_length + 2):
for node in graph.nodes_list[i]:
score = f... |
import imsearch
import unittest
from unittest.mock import patch
class TestInit(unittest.TestCase):
@patch('imsearch.config_init')
@patch('imsearch.Index')
def test_init(self, mock_index, config_init_mock):
instance = mock_index()
instance.name = 'test'
index = imsearch.init('tes... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_index = [(v, index) for index, v in enumerate(nums)]
num_index.sort()
begin, end = 0, len(nums) - 1
while(begin < end):
curr = num_index[begin][0] + num_index[end][0]
if(curr == t... |
import Foundation
from PyObjCTools.TestSupport import TestCase, min_os_level
class TestNSURLProtectionSpace(TestCase):
def testConstants(self):
self.assertIsInstance(Foundation.NSURLProtectionSpaceHTTPProxy, str)
self.assertIsInstance(Foundation.NSURLProtectionSpaceHTTPSProxy, str)
self.as... |
import numpy as np
from gym_game.envs.active_vision_env import GridUtil
screen_height = 400
screen_width = 800
grid_util = GridUtil(grid_length_x=3, grid_length_y=4, screen_height=screen_height, screen_width=screen_width)
"""
Range x:
0:[0-266.67] 1:[266.67-533.33] 2:[533.33-800]
Range y:
0:[0-100] ... |
#
# PySNMP MIB module NETFINITYMANAGER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETFINITYMANAGER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:08:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
"""An example script that moves to the control can root directory, then creates
a DATA directory, then creates a subdirectory titled by YYYYMMDD, then creates
a log, power cycles the sensors for 30 seconds, then closes the log.
"""
from datetime import datetime,timezone
from martech.sbs.thetis import THETIS
import time... |
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme_github_versions"
# Options for the sphinx rtd theme, use DLS blue
html_theme_options = dict(style_nav_header_background="rgb(7, 43, 93)")
|
#-----------------------------------------------------------------------------
# Copyright (c) 2014, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------------... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 math
def main() -> None:
# if k == 1, infinity
# if k >= 2
# enumerate all lines passing each two coorinate pairs.
# O(N^2)
# for each line, check how many coodinates passing the line.
# store katamuki(dx, dy) divided by gcd and y0 (when x = 0)
# y0 (dx, y * dx - x * dy)... |
from hiargparse import ArgumentParser, Namespace
from hiargparse import ArgsProvider, Arg, ChildProvider
from typing import Optional, List
class Tire:
@classmethod
def get_args_provider(cls) -> ArgsProvider:
return ArgsProvider(
args=[
# type can be specified; if not, defau... |
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
# Full license terms provided in LICENSE.md file.
import sys
sys.path.append('third_party/models/')
sys.path.append('third_party/models/research')
sys.path.append('third_party/models/research/slim')
#from PIL import Image
#import matplotlib.pyplot as plt
i... |
#!/bin/python3
#====================================================
# MODULES
#====================================================
from arsenalgear import mathematics as mt
#====================================================
# Mathematics
#====================================================
def mathemati... |
import pyaudio
from matplotlib import pyplot as plt
from Source.IO.Sync import *
import numpy as np
import wave
from scipy import signal
CHUNKSIZE = int(44100//0.25) # fixed chunk size
sync = createSyncSignal()
success = createSuccessSignal()
error = createErrorSignal()
# initialize portaudio
p = pyaudio.PyAudio()... |
# -*- coding: utf-8 -*-
from .lib import *
class FundingInstrument(MoipEntity):
def __init__(cls, **kw):
cls.__metadata__ = {}
# FIELDS
cls.method = String(max=65)
cls.creditCard = Obj(context=cls, key='creditCard', name='CreditCard')
cls.boleto = Obj(context=cls, key='boleto', name='Boleto')
cls.onlin... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="py-messenger",
version="1.2.0",
author="Vadym Mariiechko",
author_email="vadimich348@gmail.com",
description="Client/server single chat messenger",
long_description=long... |
# A executer depuis python manage.py shell
from collections import defaultdict
from centre.models import CentreAmbulatoire
import pandas, geopandas
import numpy as np
from shapely.ops import nearest_points
def get_cva():
df = pandas.read_excel("Referentiel_centres_vacci_20210421.xlsx")
df.drop(df[~df.TYPOLOG... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (C) eranroz
#
# Distributed under the terms of the MIT license.
import datetime
import MySQLdb
import pywikibot
familyGadgets = dict() # family -> (gadget -> [(lang, users)])
def fillStatsForCluster(host, dbList):
clusterHost = cluster
conn = MySQLdb.connect(host=... |
from .unicornafl import uc_afl_fuzz, uc_afl_fuzz_custom, monkeypatch, UcAflError, UC_AFL_RET_OK, UC_AFL_RET_ERROR, UC_AFL_RET_CHILD, UC_AFL_RET_NO_AFL, UC_AFL_RET_CALLED_TWICE, UC_AFL_RET_FINISHED
# Compatibility
from unicorn import * |
# coding: utf-8
from __future__ import absolute_import
from flask import json
from six import BytesIO
from openapi_server.test import BaseTestCase
class TestGenerationController(BaseTestCase):
"""GenerationController integration test stubs"""
def test_generation_list(self):
"""Test case for genera... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
import digit
setup(name=digit.__name__,
version=digit.__version__,
author='Pongsakorn Sommalai',
author_email='bongtrop@gmail.com',
license='MIT',
url='https://github.com/bongtrop/digit',
description='Dig git... |
# Based on pygments documentation
from pygments.lexer import RegexLexer, bygroups
from pygments.token import *
__all__ = ['PrometheusLexer']
class PrometheusLexer(RegexLexer):
name = 'Prometheus'
aliases = ['prom', 'prometheus']
filenames = ['*.prom']
tokens = {
'root': [
(r'^#.*$... |
#!/usr/bin/env python3
# type: ignore
import os
import argparse
import signal
import sys
import cereal.messaging as messaging
from cereal import log
from selfdrive.monitoring.hands_on_wheel_monitor import HandsOnWheelStatus
from selfdrive.controls.lib.events import Events
HandsOnWheelState = log.DriverMonitoringStat... |
from django.urls import path
from daroca.apps.orders import views
app_name = 'orders'
urlpatterns = [
path('add/', views.add, name='add'),
]
|
from glob import glob
from os.path import join
from collections import defaultdict
import pydicom
import subprocess as sp
import tempfile
import nibabel as nib
import numpy as np
import pandas as pd
def load_forum_data(xml_dir, dcm_dir, out_dir):
defult_tmp_dir = tempfile._get_default_tempdir()
xml_paths = s... |
from coyote_framework.webdriver.webdriverwrapper.support import JavascriptExecutor
__author__ = 'justin'
from selenium.common.exceptions import WebDriverException
from coyote_framework.log import Logger
class WebDriverWrapperException(WebDriverException):
def __init__(self, driver_wrapper, msg='WebDriverWrapp... |
'''
This code is implemented to calculate the similarity between images.
Use cosin distance for image and point clouds
Use Hash distance + Histogram distance between images
'''
import sys
sys.path.append("..")
from PIL import Image
import cv2
from numpy import average, linalg, dot
## cosin distance
def get_thumbna... |
display = {
0: 'ABCEFG',
1: 'CF',
2: 'ACDEG',
3: 'ACDFG',
4: 'BCDF',
5: 'ABDFG',
6: 'ABDEFG',
7: 'ACF',
8: 'ABCDEFG',
9: 'ABCDFG'
}
solve_it = {
'a': 'C',
'b': 'F',
'c': 'G',
'd': 'A',
'e': 'B',
'f': 'D',
'g': 'E'
}
def part1(input_str: str) -> None... |
import numpy as np
from MLlib.activations import sigmoid
class MeanSquaredError():
"""
Calculate Mean Squared Error.
"""
@staticmethod
def loss(X, Y, W):
"""
Calculate loss by mean square method.
PARAMETERS
==========
X:ndarray(dtype=float,ndim=1)
... |
import taco.common.exceptions
class MutexException(taco.common.exceptions.DataDictException):
pass
class MutexLockFailedException(MutexException):
def __init__(self, lock_name, holder, ttl, exc=None):
data_dict = {
'lock_name': lock_name,
'holder': holder,
'ttl': ... |
import os
import sys
import json
import sqlite3
from os import listdir, makedirs
from os.path import isfile, isdir, join, split, exists, splitext
from nltk import word_tokenize, tokenize
import traceback
EXIST = {"atis", "geo", "advising", "yelp", "restaurants", "imdb", "academic"}
def convert_fk_index(data):
fk_... |
####
# This is the script for storing the schema of your TerminusDB
# database for your project.
# Use 'terminusdb commit' to commit changes to the database and
# use 'terminusdb sync' to change this file according to
# the exsisting database schema
####
"""
Title: Phonebook for Awesome Startup
Description: Database st... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def plotRecursiveFunction(T, X, t1, t2):
plt.plot(T[t1:t2], X[t1:t2], 'ro')
plt.title("Mackey-Glass time series")
plt.xlabel("t")
plt.ylabel("x")
plt.show()
def plotPredictions(prediction, trueValue):
plt.plot(trueValue, 'ro'... |
import io
import gym
import numpy as np
import torch
from .pg_model import generate_pg_default_models
from ..algorithm import Algorithm
from ..util import ensure_tensor
class PGSolver(Algorithm):
def __init__(
self,
observation_space,
action_space,
models=None,
learning_r... |
number_of_guests = int(input())
price_for_person = float(input())
budget = float(input())
for_person_discount = 0
cake_price = budget - budget * 90 / 100
if 10 <= number_of_guests <= 15:
for_person_discount = price_for_person - price_for_person * 15 / 100
elif 15 < number_of_guests <= 20:
for_person_discount... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
from enum import Enum
from typing import Optional
class ActionName(Enum):
"""
Name of the action.
Can be defined by user in the per-package config file and used to overwrite the default
implementation.
New action nee... |
"""
You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:
Hello firstname lastname! You just delved into python.
Input Format
The first line contains the first name, and the second line contains the last name.
Constraints
The length of the f... |
# 2020.03.13
# Feeling a bit anxious recently, but I'm back :)
# Problem Statement:
# https://leetcode.com/problems/clone-graph/
# Referred to the DFS solution here:
# https://leetcode.com/problems/clone-graph/discuss/42309/Depth-First-Simple-Java-Solution
"""
# Definition for a Node.
class Node:
def __init__(self... |
import lxml.etree as et
import moment
def process_xpath(xpaths, *preprocessors):
def _process_xpath(root):
nonlocal xpaths
if type(xpaths) == str:
xpaths = (xpaths,)
for xpath in xpaths:
nodes = root.xpath(xpath)
if not nodes:
import ipdb... |
import logging
import random
import time
from datetime import datetime, timezone, timedelta
import pytz
import requests
from bs4 import BeautifulSoup as bS
logger = logging.getLogger('root')
def get_current_time():
try:
jamaica = pytz.timezone('Jamaica')
t = datetime.now(tz=jamaica)
curr... |
import pickle
import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.callbacks import ModelCheckpoint
from pathlib import Path
import numpy as np
import json
class CustomTensorBoard(TensorBoard):
"""
Extends tensorflow.keras.callbacks TensorBoard
Custom tensorboar... |
import requests
from datetime import datetime
import smtplib
"""
1XX: Hold None
2XX: Here You Go
3XX: Go Away
4XX: You Screwed Up
5XX: I Screwed Up
https://httpstatuses.com/
"""
MY_LAT = 25.032969
MY_LONG = 121.565414
def is_iss_overhead():
response = requests.get(url="http://api.open-notify.org/iss-now.json")
... |
import pdb
import numpy as np
import operator
import copy
import csv
# Binary (+1, -1) prediction. This assumes that the data points are
# the ROWS of the matrix!! The last column of the data matrix are the
# labels.
class DTN:
N_THRESHOLD = 4 # don't split if node has fewer examples than this
H_THRESHOLD =... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
medianprops = dict(color="r")
whiskerprops = dict(linestyle='--')
df = pd.read_csv('/home/jordibisbal/WS18-MSc-JordiBisbalAnsaldo--NetworkSlicing/evaluation/experiments/1/blockTime/blockTime.csv')
dfx=df[['InP1', 'InP2','InP3','InP4','InP5']]
da... |
import itertools
from typing import Any, Callable, Optional, Tuple, Type, Union
import pytest
from antidote import Constants, Factory, Provide, Service, world, service
from antidote._compatibility.typing import Protocol
from antidote.core import Wiring
class Interface:
pass
class FactoryOutput:
pass
cla... |
import logging
import pickle
import re
from functools import lru_cache
from pathlib import Path
from typing import NamedTuple, Optional
import requests
from cartopy.crs import PlateCarree
from ...core.mixins import ShapelyMixin, PointMixin
class AirportNamedTuple(NamedTuple):
alt: int
country: str
iata... |
# -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... |
#!/usr/bin/env python3
import asyncio
import os
from datetime import datetime, timedelta
from pngme.api import AsyncClient
async def get_net_cash_flow(
api_client: AsyncClient,
user_uuid: str,
utc_starttime: datetime,
utc_endtime: datetime,
) -> float:
"""Compute the net cash flow for a user ove... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.