content stringlengths 5 1.05M |
|---|
import json, git, os, shutil
from . import db,config
from .errors import *
def exportSnapshot(inCaseName,inSnapshotName,inFile):
data = db.dump(inCaseName,inSnapshotName)
with open(inFile, 'w') as outfile:
json.dump(data, outfile)
def importSnapshot(inCaseName,inFile):
with open(inFile, 'r') as ... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-d... |
import pytest
import responses
import status
from django.urls import reverse
from apps.tickets.models import Purchase
pytestmark = pytest.mark.django_db
def test_event_list(admin_client, event):
url = reverse('tickets:event_list')
response = admin_client.get(url)
assert response.status_code == status.HT... |
from app.admin2.views import admin # noqa
|
from django.conf.urls import url
from . import views
app_name = 'tools'
urlpatterns = [
url(r'^$', views.overview, name='overview'),
url(r'^create/$', views.create_tool, name='create'),
url(r'^delete/(\d+)/$', views.delete_tool, name='delete'),
url(r'^edit/(\d+)/$', views.edit_tool, name='edit'),
... |
import numpy as np
from imageio import imread
from pathlib import Path
from typing import List, Optional, Tuple, Union
from napari_imc.io.base import FileReaderBase, ImageDimensions
from napari_imc.models import IMCFileModel, IMCFileAcquisitionModel, IMCFilePanoramaModel
try:
import zarr
except:
zarr = None
... |
import tensorflow as tf
class MaskedACC(tf.keras.metrics.Metric):
def __init__(self, name="Accuracy", **kwargs):
super(MaskedACC, self).__init__(name=name, **kwargs)
self.acc_value = tf.constant(0.)
def update_state(self, y_true, y_pred, sample_weight=None):
real = tf.slice(y_tru... |
# -*- coding: utf-8 -*-
"""Version-check script."""
import os
import sys
import codecs
from art.art_param import *
Failed = 0
VERSION = "5.2"
README_ITEMS = ['<td align="center">{0}</td>'.format(str(FONT_COUNTER)),
'<img src="https://img.shields.io/badge/Art List-{0}-orange.svg">'.format(str(ART_COUNT... |
def language_page(lang):
return "https://www.opensubtitles.org/de/search/sublanguageid-{}".format(lang)
def movie_page(movie):
return "https://www.opensubtitles.org/en/subtitles/{}".format(movie)
|
# Copyright 2022 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
emp1 = [8, 24]
emp2 = [8, 12]
totalhours = [0, 24]
filledhours = [0, 0]
|
from datetime import datetime
from typing import List, Tuple, Dict, Any, Iterable, Optional
import attr
import consts
import tags
@attr.s()
class ModelMeta:
id = attr.ib(validator=attr.validators.instance_of(str))
title = attr.ib(validator=attr.validators.instance_of(str))
author = attr.ib(validator=att... |
from collections import defaultdict
from contextlib import ExitStack
from datetime import date, datetime
from unittest.mock import Mock, patch
import pytest
import pytz
from todoist.models import Item, Project
from synctogit.service import ServiceAPIError, ServiceTokenExpiredError
from synctogit.todoist import models... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from .agent import DDPG
from .amc_env import AMCEnv
|
""" Handles scheduling of data and news updates requested from the front end.
Attributes:
log (Logger): The logger for the covid_dashboard.
scheduler (scheduler): The sched scheduler object.
scheduled_events (list): A list of dictionaries of scheduled events.
"""
import sched
import time
import logging
fr... |
'''This program provides functions used in census_geocoder.py'''
import urllib.request, urllib.parse, urllib.error
import ssl
import json
import numpy as np
import pandas as pd
def ignore_ssl():
'''Returns context to ignore SSL certificate errors'''
ctx = ssl.create_default_context()
ctx.check_hostna... |
# @Author: charles
# @Date: 2021-06-05 11:06:90
# @Email: charles.berube@polymtl.ca
# @Last modified by: charles
# @Last modified time: 2021-06-05 11:06:27
import numpy as np
import matplotlib.pyplot as plt
from pydlc import dense_lines
if __name__ == "__main__":
# Generate random synthetic time series
... |
import logging
import requests
class SomethingWrongError(Exception):
pass
def _extract_bike_location(bike, lon_abbrev='lon'):
"""
Standardize the bike location data from GBFS. Some have extra fields,
and some are missing fields.
Arguments:
bike (dict[str, str]): A GBFS bike object as it appears in f... |
import os
import time
import random
import pygame
pygame.font.init()
# Main window
VERSION = "1.0"
WIDTH, HEIGHT = 750, 750
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")
# loading images
RED_SPACE_SHIP = pygame.image.load(
os.path.join("assets/", "pixel_ship_red_small... |
#
# PySNMP MIB module RIVERSTONE-INVENTORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-INVENTORY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:49:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return "%s" % (self.name)
class Author(models.Model):
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
def __str__... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-09-01 19:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instaapp', '0002_auto_20190901_1701'),
]
operations = [
migrations.AddFiel... |
#!/usr/bin/python3
from socket import * #importing all
host = "127.0.0.1" # setting the host on port
port = 9999
# open the socket
s = socket(AF_INET, SOCK_STREAM, 0)
# where AF_INET is the type of addresses that socket can communicate with = IPv4
# SOCK_STREAM - Connection based protocol -> TCP
# third param: 0 (d... |
from mbed.generation import make_line_mesh
from mbed.preprocessing import refine
import numpy as np
def test():
coords = np.array([[0, 0], [1, 0], [1, 0.2], [1, 0.5], [1, 0.7], [1, 1], [0, 1.]])
mesh = make_line_mesh(coords, close_path=True)
rmesh, mapping = refine(mesh, threshold=0.6)
x = mesh.coor... |
#
# Copyright (c) 2016, deepsense.io
#
# 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 w... |
from __future__ import division, print_function
import json
import os
import sys
from video_jpg_wedding import VIDAUG_BATCHES
def convert_csv_to_dict(csv_path, subset):
keys = []
key_labels = []
with open(csv_path, 'r') as fp:
lines = fp.read().splitlines()
for l in lines:
to... |
"""
This module calculates the Turbulence and Systemic Risk indicators.
"""
class Calculate:
"""
Calculates the Turbulence and Systemic Risk indicators.
"""
def __init__(self):
self.recession_start_dates = ['2001-04-01', '2008-01-01', '2020-03-01']
self.recession_e... |
##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Redistribution and use in source and binary ... |
"""create an address table
Revision ID: b2ec3f7fb212
Revises:
Create Date: 2017-10-14 15:35:18.647291
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b2ec3f7fb212'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table... |
"""Settings"""
import sys
import os
import logging
from logging.handlers import RotatingFileHandler, SMTPHandler
from flask import Flask, request
from config import BaseConfiguration
# For visibility of folder
sys.path.insert(0, os.path.join('./../algorithms'))
def register_logger(app, logs_dir):
... |
'''
Bubbles Add-on
Copyright (C) 2016 Exodus
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 3 of the License, or
(at your option) any later version.
This program is distribute... |
dirs = [{"^": 1j, ">": 1, "v": -1j, "<": -1}[c] for c in open("input_3", "r").readline().strip()]
# Part 1:
print("Part 1:", len(set(sum(dirs[:i]) for i in range(len(dirs) + 1))))
# Part 2:
visited_by_santa = set(sum(dirs[: 2 * i : 2]) for i in range(len(dirs[::2]) + 1))
visited_by_robos = set(sum(dirs[1 : 2 * i : ... |
from BusinessLogicLayer.cluster.master import *
class ActionXjCloud(ActionMasterGeneral):
def __init__(self, register_url='https://www.xjycloud.xyz/auth/register', silence=True):
super(ActionXjCloud, self).__init__(register_url=register_url, silence=silence, email='@qq.com', life_cycle=62,
... |
bl_info = {
"name": "keQuickScale",
"author": "Kjell Emanuelsson",
"category": "Modeling",
"version": (1, 0, 3),
"blender": (2, 80, 0),
}
import bpy
from mathutils import Vector
from .ke_utils import average_vector
class VIEW3D_OT_ke_quickscale(bpy.types.Operator):
bl_idname = "view3d.ke_quick... |
"""
setup.py
written in Python3
author: C. Lockhart <chris@lockhartlab.org>
"""
# import setuptools # noqa
import numpy as np
from numpy.distutils.core import Extension, setup
from numpy.distutils.misc_util import Configuration
import os.path
# Read version
with open('version.yml', 'r') as f:
data = f.read().spl... |
# -*- coding: utf-8 -*-
import unittest
from pythonrv import rv
class TestEventNext(unittest.TestCase):
def test_event_next_called_should_be(self):
class M(object):
def m(self):
pass
@rv.monitor(m=M.m)
def spec(event):
event.next_called_should_be(ev... |
###############################################################################
#
# Copyright 2014 by Shoobx, Inc.
#
###############################################################################
import unittest
import tempfile
import os
import shutil
import textwrap
from migrant import repository
class Repository... |
"""APIs from ml.vision.tranforms and ml.audio.transforms
"""
from .api import * |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#coding: utf-8
from unittest import TestCase
from django.core.cache import cache
from cache_utils.decorators import cached
from cache_utils.utils import sanitize_memcached_key, _func_type, _func_info
def foo(a,b):
pass
class Foo(object):
def foo(self, a, b):
pass
@classmethod
def bar(cls, x)... |
import numpy as np
import cv2
#image = cv2.imread("_data/blue_marker.jpg")
def detect_color(image, color):
# convert image from BGR to HSV (hue-saturation value)
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# set ranges for red
red_lower = np.array([136, 87, 111], np.uint8)
red_upper = np... |
import time, os, sys, shutil
# for math and plotting
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
#%matplotlib notebook
#%matplotlib widget
from itertools import compress # for list selection with logical
from tqdm import tqdm
from multiprocessing import Process
# ALLSO ... |
import arabic_reshaper
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
import seaborn as sns
import sys
import warnings
from bidi.algorithm import get_display
from matplotlib.backends import backend_gtk3
from matplotlib.patches import Rectangle
from iran_stoc... |
a=int(input('Enter the number:\n'))
count=0
if a==0:
count +=1
else:
while a>0:
a *= 0.1
a = int(a)
count += 1
print(count)
|
from django.contrib import admin
from article.models import Article, ArticleHeading, ArticleFeedback, ArticleEdit, ArticlePost
# Register your models here.
class ChoiceInline(admin.StackedInline):
model = ArticleHeading
extra = 1
class ArticleAdmin(admin.ModelAdmin):
fieldsets = [
(None, ... |
from Mongo import *
from Mongo.Gaming import *
from Mongo.Gaming.Imports import *
|
from flask import Flask, request
import bs4 as bs
import requests
import json
import os
import datetime
import time
import pytz
import threading
app = Flask(__name__)
debug_print_on = False
######################### Global Variables #########################
f = open('./data.json', "r")
db = json.loads(f.read())
f.cl... |
BATCH_SIZE = 128
LEARNING_RATE = 0.1
CRUSH_RATE = 0.0001
NUM_CORNERS = 4
ISIZE = 32
CHANNELS = 1
NUM_CLASSES = 13 * 4
SAVE_PATH = "./model"
SETS = ["train", "test"]
NUM_THREADS = 12 |
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponseRedirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from . import forms
from . models import Ticket
# Create your views here.
@login_required
... |
def main() -> None:
import sys
from .scanner import PEiDScanner, format_as_katc_peid
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} input_file")
return
peid_scanner = PEiDScanner()
scan_result = peid_scanner.scan_file(sys.argv[1])
print(format_as_katc_peid(scan_res... |
import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets as widgets
import numpy as np
def heatmap(x, y, size):
'''
https://towardsdatascience.com/better-heatmaps-and-correlation-matrix-plots-in-python-41445d0f2bec
'''
fig, ax = plt.subplots()
# Mapping from column names to integer co... |
from deepdab.ai import *
class TDOneTabularPolicy(TabularPolicy):
def __init__(self, board_size, learning_rate=0.0, gamma=0.0, epsilon=0.0, initial_state_value=0.0,
table_file_path=None, softmax_action=False, temperature=0.0):
super(TDOneTabularPolicy, self).__init__(board_size=board_size... |
from decimal import Decimal
import itertools
import pandas
import collections
from adt import AnnualChange
import random
def namedtuple_with_defaults(typename, field_names, default_values=()):
T = collections.namedtuple(typename, field_names)
T.__new__.__defaults__ = (None,) * len(T._fields)
if isinstance(... |
import consumer
import sensor
import analyzer
import threading
import dashboard
import logging
import sys
import sched, time
import ids
import terminaloutput
#logging.getLogger().setLevel(logging.INFO)
IDS_CHECK_INTERVAL = 5
class Monitor:
def __init__(self):
self.consumers = []
s = sensor.Sensor()
h... |
# Copyright 2015 gRPC authors.
#
# 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... |
import numpy as np
from rlgym.utils import RewardFunction, math
from rlgym.utils.common_values import BALL_RADIUS, CAR_MAX_SPEED
from rlgym.utils.gamestates import GameState, PlayerData
class LiuDistancePlayerToBallReward(RewardFunction):
def reset(self, initial_state: GameState):
pass
def get_rewar... |
import numpy as np
import cv2
import imutils
import math
from gpio_controller.ServoController import ServoController
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-v', '--video', default=1)
args = vars(ap.parse_args())
servo_controller = ServoController()
servo_controller.init()
theta = 0
speed = 0... |
class PyGridClientException(Exception):
def __init__(self, message: str) -> None:
super().__init__(message)
class RequestAPIException(Exception):
def __init__(self, message: str) -> None:
message = "Something went wrong during this request: " + message
super().__init__(message)
|
import sys
import os
sys.path.append(os.pardir)
import reg3d_transformations as reg3d_T
from numpy import linalg as LA
import transformations as tf
#******************** BH ********************
# cvg_root = "/Users/isa/Experiments/reg3d_eval/cvg_eo_data"
# dan_root = "/Users/isa/Experiments/reg3d_eval/BH_2006/orig... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... |
""" Plotting class for IRR/IFR
Plots the output of :py:func:`~agg_dyn.stats.utils.score_points`
Classes:
* :py:class:`ReliabilityPlotter`: Plot IRR and IFR barplots
Functions:
* :py:class:`plot_roc_curve`: Make ROC curve plots
* :py:class:`plot_pr_curve`: Make P/R curve plots
"""
# Imports
import json
# 3rd par... |
import numpy as np
import tensorbackends
from .statevector import StateVector
def computational_zeros(nsite, *, backend='numpy'):
backend = tensorbackends.get(backend)
tensor = backend.zeros((2,)*nsite, dtype=complex)
tensor[(0,)*nsite] = 1
return StateVector(tensor, backend)
def computational_ones... |
import logging
import os
from pathlib import Path
from uvicorn.supervisors.basereload import BaseReload
logger = logging.getLogger("uvicorn.error")
class StatReload(BaseReload):
def __init__(self, config, target, sockets):
super().__init__(config, target, sockets)
self.reloader_name = "statreloa... |
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Text, Boolean, UniqueConstraint
from datetime import datetime
Base = declarative_base()
_e... |
import logging
import re
import time
from urllib.parse import parse_qs
from urllib.parse import urlparse
import pandas as pd
import requests
from bs4 import BeautifulSoup
from covidata import config
from covidata.persistencia.dao import persistir_dados_hierarquicos
def pt_PortoAlegre():
url = config.url_pt_Port... |
import numpy as np
def fcann2_train(X, Y, nhidden=5, param_niter=1e5, param_delta=0.05, param_lambda=1e-3):
w1 = np.random.randn(X.shape[1], nhidden) * 0.01
b1 = np.random.randn(1, nhidden) * 0.01
w2 = np.random.randn(nhidden, max(Y) + 1) * 0.01
b2 = np.random.randn(1, max(Y) + 1) * 0.01
Y_ = np... |
from unittest import TestCase
from camunda.utils.auth_basic import AuthBasic, obfuscate_password
class TestAuthBasic(TestCase):
def test_auth_basic(self):
auth_basic = AuthBasic(**{
"username": "test",
"password": "test",
})
self.assertEqual(auth_basic.token, 'Basi... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
from cgitb import html
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from .models import Document, Create_page, Demo_page
import json
from datetime import date
import datetime
# Create your views here.
def send_html_element_from_python_function(request):... |
from setuptools import setup, find_packages
setup(
name='frasco-angular',
version='0.7.1',
url='http://github.com/frascoweb/frasco-angular',
license='MIT',
author='Maxime Bouroumeau-Fuseau',
author_email='maxime.bouroumeau@gmail.com',
description="Angular integration for Frasco",
packa... |
from contracting_process.resource_level.consistent.period_duration_in_days import calculate
item_test_undefined = {
"tender": {
"tenderPeriod": {"startDate": "2019-08-14T16:47:36+01:00"},
"enquiryPeriod": {"startDate": "2019-08-14T16:47:36+01:00", "endDate": None, "durationInDays": 2},
}
}
de... |
# asyncio_wait_timeout_without_cancel_continue.py
import asyncio
async def phase(i):
print('now in phase {}'.format(i))
try:
await asyncio.sleep(0.1 * i)
except asyncio.CancelledError:
print('phase {} canceled'.format(i))
raise
else:
print('done with phase {}'.format(i)... |
"""Management of configuration from environment variables."""
import dataclasses
import re
from json import JSONDecodeError
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional, cast
from pydantic import (
AnyHttpUrl,
AnyUrl,
BaseSettings,
Field,
FilePath,
PositiveInt,
... |
#!/usr/bin/env python3
"""Dynamic dns to ip address firewall rule creator.
Resolve dynamic dns names into ips and automatically create/destroy
firewall rules. Script requires to run as super user in order to be able to
create the firewall rules.
Requirements:
The following packages should be installed and enable... |
from .index import IndexView
from .media import MediaView
from .tag_image import TagImageView
from .tag_images import TagImagesView
from .tags_list import TagsListView
from .similar_images import SimilarImagesView
|
"""File containing class that abstracts a collection of widgets.
It can be used to swap between collections of widgets (screens) in a py_cui
"""
# Author: Jakub Wlodek
# Created: 12-Aug-2019
# TODO: Should create an initial widget set in PyCUI class that widgets are added to by default.
import shutil
import py... |
import pytest
from gamestonk_terminal.cryptocurrency.onchain import blockchain_view
@pytest.mark.vcr
@pytest.mark.record_stdout
def test_display_btc_circulating_supply(mocker):
# MOCK CHARTS
mocker.patch.object(target=blockchain_view.gtff, attribute="USE_ION", new=True)
mocker.patch(target="gamestonk_ter... |
# http://localhost:5555/?unvoweled=ARABIC_WORD
import mishkal.tashkeel
from flask import Flask, request
app = Flask(__name__)
voweler = mishkal.tashkeel.TashkeelClass()
def get_vowels(unvoweled):
voweled = voweler.tashkeel(unvoweled)
return voweled
@app.route('/tashkeel', methods=["GET"])
def set_vowels()... |
'''
Write a program which can compute the factorial of a given numbers. Use recursion to find it.
Hint: Suppose the following input is supplied to the program:8
Then, the output should be:40320
'''
def fact (x):
if (x == 0):
return (1)
else :
return (x * fact(x-1))
n = input('Ent... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2005-2010 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~... |
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present GlastHeim.pe
"""
from django.urls import path, re_path
from apps.includes.sidebar.views import SidebarList
urlpatterns = [
path('sidebar', SidebarList.as_view(), name='sidebar.index'),
] |
from pathlib import Path
def get_files(root, extensions, recursive=True):
if isinstance(extensions, str):
extensions = [extensions]
root = Path(root)
all_files = root.rglob('*') if recursive else root.glob('*')
return [
x for x in all_files if any(x.name.endswith(y) for y in extensions... |
import numpy as np
import time
import imutils
import cv2
avg = None
video = cv2.VideoCapture("1.mp4")
xvalues = list()
yvalues = list()
motion = list()
count1 = 0
count2 = 0
def find_majority(k):
myMap = {}
maximum = ('', 0) # (occurring element, occurrences)
for n in k:
if n in myMap: myMap[n] ... |
#
# Copyright (c) 2020 Lucas Lehnert <lucas_lehnert@brown.edu>
#
# This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project.
#
import numpy as np
from itertools import product
import rlutils as rl
import os
import os.path as osp
import multiprocessing as mp
from... |
from brownie import accounts, web3, Wei, chain
from brownie.network.transaction import TransactionReceipt
from brownie.convert import to_address
import pytest
from brownie import Contract
from settings import *
######################################
# Deploy Contracts
######################################
@pytest.f... |
"""
Functions that interface with the TF Serving service go here
"""
import grpc
import os
import simplejson as json
import numpy as np
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2, get_model_metadata_pb2, prediction_service_pb2_grpc
from tensorflow_serving.apis.model_pb2 import ModelSpec... |
import torch
from transformers import AdamW, get_linear_schedule_with_warmup
class BaseModel(torch.nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.from_pretrained()
def save_pretrained(self, save_dir):
self.model.save_pretrained(save_dir)
... |
import unittest
import io
from remcall.schema import Schema, Enum, Record, Interface, Method, string, float32, uint32, uint16, void, date, datetime, Array
from remcall import SchemaReader, read_schema, SchemaWriter, schema_to_bytes
Status = Enum('Status', ['Registered', 'Activated', 'Locked'])
User = Interface('User',... |
"""Problem 69
07 May 2004
Euler's Totient function, φ(n) [sometimes called the phi function], is
used to determine the number of numbers less than n which are
relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all
less than nine and relatively prime to nine, φ(9)=6.
n Relatively Prime φ(n) n/φ(n)
2 1 1 ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Adres',
fields=[
... |
bl_info = {
"name": "Reload Addon",
"blender": (2, 83, 0),
"category": "Development",
}
import bpy
from bpy.props import StringProperty
import time
import os
class ReloadOperator(bpy.types.Operator):
bl_idname = "wm.reload_addon"
bl_label = "Reload Addon"
def execute(self, context):
r... |
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env('DJANGO_SECRET_KEY', de... |
from discord.ext.commands import Cog, command, is_owner
from discord import Color, Embed, File
from sys import version_info
from asyncpg.exceptions import UniqueViolationError
from mcstatus import MinecraftServer
from socket import gethostbyname, timeout, gaierror
from matplotlib.pyplot import subplots, xlabel, y... |
# -*-coding: utf-8-*-
# @Author : Charlesxu
# @Email : charlesxu.ai@gmail.com
|
from requests import ConnectionError, Timeout
class AlephException(Exception):
def __init__(self, exc):
self.exc = exc
self.response = None
self.status = None
self.transient = isinstance(exc, (ConnectionError, Timeout))
self.message = str(exc)
if hasattr(exc, "respo... |
from django import template
from metashare.repository.models import corpusInfoType_model, \
toolServiceInfoType_model, lexicalConceptualResourceInfoType_model, \
languageDescriptionInfoType_model
register = template.Library()
class ResourceLanguages(template.Node):
"""
Template tag that allows to dis... |
"""Integration with I Done This."""
from __future__ import unicode_literals
import json
import logging
from django.utils.functional import cached_property
from django.utils.six.moves.urllib.error import HTTPError, URLError
from django.utils.six.moves.urllib.request import urlopen
from django.utils.translation import... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from segm_benchmark.utils.encoding import scaled_l2, aggregate
class Encoding(nn.Module):
r"""
Encoding Layer: a learnable residual encoder.
Args:
D: dimention of the features or feature channels
K: number of codeswords
... |
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2015 Emmanuel Gil Peyrot
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
import asyncio
import logging
from uuid import uuid4
from slixmpp.plugins import BasePlugin, register_plugin
from slixmpp import future_wrapper, Iq, Message
from sl... |
from classtoolz import Slotted, Typed, Immutable, Cached
class Person(Slotted, Typed, Immutable, Cached):
""" A Person class
Example for Slotted, Typed, Immutable and Cached mixins
>>> Alice = Person('Alice', 25)
>>> Alice
Person(name=Alice, age=25)
>>> Alice.age = 26
Traceback (most rec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.