content stringlengths 5 1.05M |
|---|
from jax import numpy as jnp
from typing import Callable
def weighted_dot(sigma_i: float, sigma_r: float, sigma_b: float) -> Callable:
"""Defines weighed dot product, i.e. <u, v> with u = [i, j]
Returns function which calculates the product given the weights.
"""
def dot(gram: jnp.ndarray, kernel: jn... |
import requests,json
from HelperTools import Debug
import os
sourceStreamInfoListUrl = os.getenv('SourceStream')
GetNotFixedStreamAPIUrl = os.getenv("NotFixedStreamAPI")
# 需要做代理的源流信息
sourceStreamInfoList = {}
def GetSourceStreamInfoList():
if sourceStreamInfoListUrl == None or sourceStreamInfoListUrl == "defa... |
import pygame as p
import dartboard
import buttonPanel
import statPanel
from dartboard import PERCENTAGES, LASTBULLSEYE
WIDTH = 800
HEIGHT = 700
BACKGROUND = p.Color("red")
MAX_FPS = 30
def main():
global throwing
p.init()
screen = p.display.set_mode((WIDTH, HEIGHT))
screen.fill(BACKGROUND)
p.dis... |
import copy
import inspect
import math
import numpy as np
import random
def create_new_children_through_cppn_mutation(pop, print_log, new_children=None, mutate_network_probs=None,
max_mutation_attempts=1500):
"""Create copies, with modification, of existing individuals in t... |
import sys
def solution(A):
difference = sys.maxsize
left = 0
right = sum(A)
for i in range(0, len(A)-1):
left += A[i]
right -= A[i]
if abs(right - left) < difference:
difference = abs(right - left)
return difference
def test_solution():
assert solutio... |
import json
def readJsonFromFile(filename):
file = open(filename, 'r')
arr = json.loads(file.read())
file.close()
return arr |
from enum import Enum
class TaskState(Enum):
# static states:
# a task can either succeed or fail
VALID = 0x0
INVALID = 0x1
# actionable states
DROP = 0x10
DONE = 0x99
class TaskConfigState(Enum):
VALID = 0x0
INVALID = 0x1
|
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data', one_hot=True)
# Path to Computation graphs
LOGDIR = './graphs'
# Start session
sess = tf.Session()
# Hyper parameters
LEARNING_RATE = 0.01
BATCH_SIZE = 1000
EPOCHS = 10
# Hid... |
#:::::::::::::::::::::::::
#::
#:: ProjectDependencies/check.py
#::_______________________
#::
#:: Author: Clement BERTHAUD
#::
#:: MIT License
#:: Copyright (c) 2018 ProjectDependencies - Clément BERTHAUD
#::
#:: Permission is hereby granted, free of charge, to any person obtaining a copy
#:: of this software and asso... |
"""
We presume that Channels is operating over a Redis channel_layer here, and use it
explicitly.
"""
from base64 import b64encode
from json import dumps
def message_to_hash(message):
message_hash = b64encode(dumps(message).encode("utf-8"))
return b"semaphore:" + message_hash
async def get_set_message_sema... |
"""
Configuration for the integration issues tests
"""
import pytest
@pytest.fixture(scope="package", autouse=True)
def xfail():
pytest.xfail("Issues tests need refactored")
|
import argparse
import json
import logging
import os
import subprocess
import tqdm
import wget
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import numpy as np
import torch
import random
def extracting_log_info(log_files, experiment, logging):
metrics_t2v = defaultdict... |
#!/usr/bin/env python
from __future__ import print_function
"""
test_split_regex_and_collate.py
"""
JOBS_PER_TASK = 5
import os
tempdir = os.path.relpath(os.path.abspath(os.path.splitext(__file__)[0])) + "/"
import sys
import re
# add grandparent to search path for testing
grandparent_dir = os.path.abspath(os.p... |
from django.views.generic import View
from core.models import Cardapio
from django.shortcuts import render
from core.outros.categoriasCardapio import categoriasCardapio
import json
class CardapioView(View):
def get(self, request, *args, **kwargs):
categoria = request.GET.get('categoria')
item_adi... |
import argparse
import logging
import os
from sentiment_analysis.src.managers.survey_replies_manager import SurveyRepliesManager
from utils.data_connection.api_data_manager import APISourcesFetcher
from utils.data_connection.source_manager import Connector
from utils.gcloud.nlp_client import NLPGoogleClient
from utils... |
import numpy as np
import os
forcing_filename = os.path.join(os.path.dirname(__file__), 'cmip6_solar.csv')
class Forcing:
forcing = np.loadtxt(forcing_filename, skiprows=7, delimiter=',')
year = forcing[:,0]
solar = forcing[:,1]
|
import os
import numpy as np
from play_model import PlayModel
class PlayAgent:
def __init__(self, params):
self.parameters = params
os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(self.parameters['tf_log_level']) #reduce log out for tensorflow
self.model = PlayModel(self.parameters)
... |
import pytest
import asyncio
from async_v20.client import OandaClient
@pytest.yield_fixture
@pytest.mark.asyncio
async def client():
oanda_client = OandaClient(rest_host='127.0.0.1', rest_port=8080, rest_scheme='http',
stream_host='127.0.0.1', stream_port=8080, stream_scheme='http',... |
"""
Defines the blueprint for the auth
"""
import uuid
import datetime
from flasgger import swag_from
from flask import Blueprint, request
from flask.json import jsonify
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_jwt_extended import (create_access_token, get_jwt_identity)
from rep... |
import numpy as np
def main():
nx = 2
ny = 3
nz = 4
def do_it(i):
return [i % nx, (i / nx) % ny, i / (nx * ny)]
def undo_it(x, y, z):
# return z + ny * (y + nx * x)
# return x + nx * (x + ny * y)
# return (x * nx * ny) + (y * ny) + z
# return (z * nx * ny... |
import utils
import euclides
def esCarmichael(p):
# p > 0
# Retorna cert si p és un nombre de carmichael, fals altrament
i = 1
while i < p:
if euclides.sonCoprimers(i, p):
if utils.potencia_modular_eficient(i, p-1, p) != 1:
return False
i += 1
if i == p:
... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
#!/usr/bin/env python
# -*- coding: utf8
from __future__ import print_function, division
from pyksc import dist
import glob
import numpy as np
import os
import plac
import sys
def main(tseries_fpath, in_folder):
ids = []
with open(tseries_fpath) as tseries_file:
for l in tseries_file:
id... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Processor for CRGA models"""
import otbApplication
from decloud.core import system
import pyotb
import unittest
from decloud.production import crga_processor
from decloud.production.inference import inference
from .decloud_unittest import DecloudTest
import datetime
d... |
#!/usr/bin/env python
# Copyright (c) 2018 Harold Wang, Ryan L. Collins, and the Talkowski Lab
# Distributed under terms of the MIT License (see LICENSE)
# Contact: Ryan L. Collins <rlcollins@g.harvard.edu>
# gnomAD credits: http://gnomad.broadinstitute.org/
"""
Helper script for workflow to calculates B-allele frequ... |
"""Lib module for daq sub units"""
pass
|
#!/usr/bin/env python
r"""Aggregate, create, and save 1D and 2D histograms and binned plots.
"""
from . import agg_plot
from . import hist1d
from . import hist2d
AggPlot = agg_plot.AggPlot
Hist1D = hist1d.Hist1D
Hist2D = hist2d.Hist2D
# import pdb # noqa: F401
# import logging
# import numpy as np
# import pandas ... |
#-- GAUDI jobOptions generated on Mon Oct 12 10:07:37 2020
#-- Contains event types :
#-- 90000000 - 3737 files - 56787251 events - 2862.54 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass: '/Real Data/Reco14/Stripping21r1'
#-- StepId : 127013
#-- StepName : Stripping21r1-M... |
"""
Customized Django model field subclasses
"""
from django.db import models
from django.db.models import fields
from django.db.models.fields.related import ManyToManyField
class CopyFromFieldMixin(fields.Field):
"""
Mixin to add attrs related to COPY FROM command to model fields.
"""
def __init__(se... |
# Aula de estrutura de repetição com variavel de controle
for c in range(0, 6):
print('oi')
print('fim')
for a in range(0, 10, 2): # o primeiro argumento e o segundo é o range de contagem, o terceiro é o metodo da contagem
print(a)
print('fim')
# Outro exemplo
for a in range(10, 0, -1): # Com uma condição d... |
from __future__ import print_function
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
#rc('text', usetex=True)
# generate data
# list of points
from matplotlib.backends.backend_pd... |
import sys
import serial
import pprint
import time
import enum
import queue
from queue import Queue
from os.path import join, dirname, abspath
from qtpy.QtCore import Slot, QTimer, QThread, Signal, QObject, Qt, QMutex
class GcodeStates(enum.Enum):
WAIT_FOR_TIMEOUT = 1
GCODE_SENT = 2
READY_TO_SEND = 3
clas... |
from urllib.parse import unquote
from flask import Flask
from flask import Response
from flask import abort
from flask import jsonify
from flask import render_template
from flask import request
from flask import send_file
from werkzeug.exceptions import BadRequest
from bootstrapper.lib import archive_utils
from boots... |
# stream.models
# Database models for the Activity Stream Items
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Wed Feb 04 10:24:36 2015 -0500
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: models.py [70aac9d] benjamin@bengfort.com $
"""
Databa... |
# files.py — Debexpo files handling functions
#
# This file is part of debexpo -
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associ... |
# -*- coding: utf-8 -*-
class BIT:
def __init__(self, size: int) -> None:
self.size = size
self._bit = [0 for _ in range(self.size + 1)]
def add(self, index: int, value: int) -> None:
while index <= self.size:
self._bit[index] += value
index += index & -index
... |
"""Mock input data for unit tests."""
from copy import deepcopy
import uuid
# no dependencies
MOCK_BASE_PATH = "a/b/c"
MOCK_DRS_URI = "drs://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_INVALID = "dr://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_LONG = (
"drs://aaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa"
"aaaaa... |
from sikuli import *
import sys
sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples')
from test_helper import TestHelper
import open_flex_from_backup, check_change
helper = TestHelper("run_tests_from_backups")
folder = "/home/vagrant/Integration-Testing-Framework/sikuli/examples/images_for_... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""File service tests."""
from io import BytesIO
def test_file_flow(
file_service, location... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from future.builtins import object
from contextlib import contextmanager
import sys
import unittest
from redis import Redis
from limpyd.database import (RedisDatabase, DEFAULT_CONNECTION_SETTINGS)
TEST_CONNECTION_SETTINGS = DEFAULT_CONNECTION_SETTINGS.... |
from .newton_divided_differences import NewtonDifDiv
from .larange import Larange
from .linear_spline import LinearSpline
from .quadratic_spline import QuadraticSpline
from .cubic_spline import CubicSpline
|
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ... |
from setuptools import setup, find_packages
setup(
name='arranger',
version='1.1.2',
description="moves each file to its appropriate directory based on the file's extension.",
author='j0eTheRipper',
author_email='j0eTheRipper0010@gmail.com',
url='https://github.com/j0eT... |
"""
Copyright 2018 Duo Security
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistribut... |
from django.apps import AppConfig
class ProntuariomedicoConfig(AppConfig):
name = 'prontuarioMedico'
|
"""
Enables the user to add an "Image" plugin that displays an image
using the HTML <img> tag.
"""
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from cm... |
import lark
import copy
import torch
class LogicParser:
""" This class defines the grammar of the STL according to
the EBNF syntax and builds the AST accordingly.
"""
_grammar = """
start: prop
prop: VAR CMP (CONST | VAR) -> atom
| _NOT "(" prop ")" -> op_not
| (prop _... |
from dash import Input, Output, callback
from dash import dcc
import dash.html as html
import dash_bootstrap_components as dbc
from pages.constants import TITLE_STYLE, PARAGRAPH_STYLE, IMG_STYLE
from utils.topic_crud import TopicCRUD
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = ... |
#!/usr/bin/python
class race:
def __init__(self, t):
self.title = t
#ACCESSORS
def titleReturn(self):
return(self.title) |
import glob
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name="mldiag",
version="0.0.1",
author="Aymen SHABOU",
author_email="aymen.shabou@gmail.com",
descript... |
#!/usr/bin/env python
import roslib
import rospy
import tf
from geometry_msgs.msg import TransformStamped
from posedetection_msgs.msg import ObjectDetection
def handle_pose(msg):
br = tf.TransformBroadcaster()
if len(msg.objects)==0:
return
p = msg.objects[0].pose
br.sendTransform((p.position.... |
#!/usr/bin/env python3
#
# Author: Jeremy Compostella <jeremy.compostella@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
... |
"""
Merged String Checker
http://www.codewars.com/kata/54c9fcad28ec4c6e680011aa/train/python
"""
def is_merge(s, part1, part2):
result = list(s)
def findall(part):
pointer = 0
for c in part:
found = False
for i in range(pointer, len(result)):
if result... |
import os
import docker.errors
import pandas as pd
import pytest
from ebonite.build.docker import create_docker_client, is_docker_running
from ebonite.core.objects.core import Model
from sklearn.linear_model import LinearRegression
from tests.client.test_func import func
def has_docker():
if os.environ.get('SKI... |
from ..value_set import ValueSet
class BmiRatio(ValueSet):
"""
**Clinical Focus:** This value set contains concepts that represent a body mass index (BMI) ratio.
**Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Procedure.
**Inclusion Criter... |
import os
import json
import tempfile
from model import VepException, VepResult
from bgcore import tsv
from bgcore.request import Request
def _ctype(value):
return value.split(",")
class VepService(object):
HOST = "beta.rest.ensembl.org"
VEP_STRAND = { "+" : "1", "-" : "-1", "1" : "1", "-1" : "-1" }
def __ini... |
from ._PlaceBox import *
from ._RemoveBox import *
|
"""Implements logic to render and validate web forms for login and user registration."""
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
"""Form for new users to log-in to... |
spanish_columns = {
"oer": "oer",
"games": "partidos",
"points_made": "puntos_a_favor",
"total_possessions": "posesiones_totales",
"minutes": "minutos",
"assists": "asistencias",
"steals": "robos",
"turnovers": "perdidas",
"2_point_percentage": "porcentaje_2_puntos",
"2_point_mad... |
import decimal
import numbers
import itertools
__all__ = [
'TRUNCATE',
'ROUND',
'DECIMAL_PLACES',
'SIGNIFICANT_DIGITS',
'NO_PADDING',
'PAD_WITH_ZERO',
'decimal_to_precision',
]
# rounding mode
TRUNCATE = 0
ROUND = 1
# digits counting mode
DECIMAL_PLACES = 2
SIGNIFICANT_DIGITS = 3
# padd... |
import os
from setuptools import setup
README = """
See the README on `GitHub
<https://github.com/uw-it-aca/uw-restclients-coda>`_.
"""
version_path = 'uw_coda/VERSION'
VERSION = open(os.path.join(os.path.dirname(__file__), version_path)).read()
VERSION = VERSION.replace("\n", "")
# allow setup.py to be run from any... |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
################################################################################
# Project: OGR NextGIS Web Driver
# Purpose: Tests OGR NGW Driver capabilities
# Author: Dmitry Baryshnikov, polimax@mail.ru
# Language: Python
#############################################... |
# Copyright (c) 2016 Rackspace Hosting 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 t... |
# coding: utf-8
# pylint: disable=W0201,C0111
from __future__ import division, unicode_literals, print_function
# standard library
import sys
import os.path
import time
import datetime
import traceback
from copy import deepcopy
from collections import OrderedDict
from itertools import cycle
from math import ceil
impor... |
#
# Copyright (c) 2010 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two lic... |
import re
import h5py
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from os.path import join,exists
from os import listdir
from paper import paper
def html_reader(input_dir):
"""
read the html file at input_dir, ... |
from .experiment import Experiment # noqa: F401
from .trial import Trial # noqa: F401
|
import os
import argparse
import imageio
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True, type=str)
args = parser.parse_args()
for file in sorted(os.listdir(os.path.join('outputs', args.name, 'particles'))):
i = int(file.replace('.bin', ''))
print('frame %d' % i, flush=True)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-20 14:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0014_add_indices'),
]
operations = [
migrations.AddIndex(
... |
###########################################################
# compare.py -Script that compares any two painting's hex
# hex values for similarity or rank in the
# frequency list and quantifies it with a
# percentage
# Author: Shaedil Dider
###########################################... |
from selenium import webdriver
from utils.logging import init_logger
from utils.s3_manager.manage import S3Manager
class SeleniumCrawler:
def __init__(self, base_url, bucket_name, key, head=False):
self.logger = init_logger()
self.bucket_name = bucket_name
self.s3_manager = S3Manager(buc... |
from ._accuracy_per_cell_type import accuracy_per_cell_type
from ._cd_ratio import cd_ratio
from ._cumulative_node import cumulative_node
from ._cumulative_node_group import cumulative_node_group
from ._dists_distr import dists_distr
from ._mean_node_per_cell_type import mean_node_per_cell_type
from ._metric_heatmap im... |
import socket
class Triton200:
"""
Create an instance of the Triton200 class.
Supported modes: IP
:param str ip_address: The IP address of the Triton 200.
:param int port_number: The associated port number of the Triton 200 (default: 33576)
:param int timeout: How long to wait for... |
import random
import itertools
import json
import networkx as nx
import sys, getopt
import dcop_instance as dcop
def generate(G : nx.Graph, dsize = 2, p2=1.0, cost_range=(0, 10), def_cost = 0, int_cost=True, outfile='') :
assert (0.0 < p2 <= 1.0)
agts = {}
vars = {}
doms = {'0': list(range(0, dsize))}
... |
#!/usr/bin/python3
"""Explode an LLVM IR dump.
Given a debug dump generated from the -print-debug-all option, split out the
dumps into multiple files, one for each phase/procedure. Example usage:
clang -c -O3 -mllvm -print-before-all mumble.c 1> err.txt 2>&1
rm -rf /tmp/dumps ; mkdir /tmp/dumps
explode-llvm-ir-... |
# https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Corpora_and_Vector_Spaces.ipynb
from gensim import corpora
# This is a tiny corpus of nine documents, each consisting of only a single sentence
documents = ["Human machine interface for lab abc computer applications",
"A survey of u... |
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu>
#
# 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 later version.
#
# Th... |
# Author: Deepak Pathak (c) 2016
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
import numpy as np
from PIL import Image
import time
import argparse
import os
import pyflow
parser = argparse.ArgumentParser(
des... |
from rect import Rect
from math import floor
class HashMap(object):
"""
Hashmap is a broad-phase collision detection strategy, which is quick
enough to build each frame.
"""
def __init__(self, cell_size):
self.cell_size = cell_size
self.grid = {}
@classmethod
def from_objec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
drawmap.py
@Purpose: draw a current map from a hdf mohid or netcdfoutput
@version: 1.0
@python version: 3.9
@author: Pedro Montero
@license: INTECMAR
@requires: matplotlib, numpy, toolkits.basemap
@date 2021/10/13
@history:
"""
import os
from common.readers.read... |
a,b=map(int,input().split())
print(-~(a+b)//2) |
# script to create relationship classes in a GeMS database
#
# Somebody who uses relationship classes more than I should look at this.
# Particularly, are the Forward and Backward labels named as usefully as possible?
# Are there other issues?
#
# Note that Validate Database script can be used to maintain refere... |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Paint')
self.setWindowIcon(QIcon('Images/Paint.png'))
self.setMaximumSize(860, 720)
self... |
# Run detection in real-time setting on a COCO-format dataset
import argparse, json, pickle
from os.path import join, isfile
from time import perf_counter
from tqdm import tqdm
import numpy as np
import torch
from pycocotools.coco import COCO
from mmcv.runner import load_checkpoint
import sys; sys.pa... |
import os
import glob
from imageai.Detection.Custom import DetectionModelTrainer
execution_path = os.getcwd()
models_path = os.path.join(execution_path, "doge-identification/models/")
data_path = os.path.join(execution_path, "doge-identification/")
# This will force tensorflow to run on the cpu
os.environ["CUDA_VISIBL... |
# This file is part of the CERN Indico plugins.
# Copyright (C) 2014 - 2020 CERN
#
# The CERN Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License; see
# the LICENSE file for more details.
from __future__ import unicode_literals
from wtforms.fields import... |
"""Error handlers."""
from werkzeug.http import HTTP_STATUS_CODES
from flask import jsonify
from muckr_api.extensions import database
class APIError(Exception):
def __init__(self, status_code, message=None, details=None):
super().__init__()
error = HTTP_STATUS_CODES.get(status_code, "Unknown err... |
from django.conf.urls import url
from .views import Dashboard
urlpatterns = [
url(r'^$', Dashboard.as_view()),
]
|
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# 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 SOFTWARE IS PROVIDED "AS I... |
from typing import List
import msgpack
from pydantic import BaseModel
import ormsgpack
class Member(BaseModel):
id: int
active: bool
class Object(BaseModel):
id: int
name: str
members: List[Member]
objects_as_pydantic = [
Object(
id=i, name=str(i) * 3, members=[Member(id=j, activ... |
#!/usr/bin/env python
from breakmywork.application import main
main()
|
import inferpy as inf
def test_parameter_in_pmodel():
# test that random variables in pmodel works even if no name has been provided
@inf.probmodel
def model():
inf.Parameter(0)
v = list(model().params.values())[0]
assert v.name.startswith('parameter')
# assert also is_datamodel is fa... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C11I13_cff import Phase2C11I13
from Configuration.Eras.Modifier_phase2_3DPixels_cff import phase2_3DPixels
from Configuration.Eras.Modifier_phase2_GE0_cff import phase2_GE0
Phase2C11I13T25M9 = cms.ModifierChain(Phase2C11I13, phase2_3DPixels, p... |
import numpy as np
class RandomParameters:
"""
Example params are in JSON format:
{
"booster": ["gbtree", "gblinear"],
"objective": ["binary:logistic"],
"eval_metric": ["auc", "logloss"],
"eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1]
}
"""
@sta... |
import sys,os,pygame
|
# Generated by Django 3.0.6 on 2020-05-25 00:02
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)... |
from tests.save_restore_cursor import SaveRestoreCursorTests
import esccmd
from escutil import knownBug
class DECSETTiteInhibitTests(SaveRestoreCursorTests):
def __init__(self):
SaveRestoreCursorTests.__init__(self)
def saveCursor(self):
esccmd.DECSET(esccmd.SaveRestoreCursor)
def restoreCursor(self):
... |
from domain.rules import game_loops
connect_game = game_loops.Game_Loops()
''' here we call the game loop function'''
connect_game.connect_four_game()
|
from flask import Flask, request, render_template, url_for, send_file
import qrcode
from PIL import Image
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/result', methods=["POST", "GET"])
def result():
if request.method == "POST":
input = request.f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.