text stringlengths 2 999k |
|---|
from screws.freeze.base import FrozenOnly
class _3dCSCG_SF_dofs_FIND(FrozenOnly):
""""""
def __init__(self, dofs):
self._dofs_ = dofs
self._freeze_self_()
def dof_at_corner_of_region(self, region_name, which_corner):
"""We find the dof as a _3dCSCG_SF_DOF instance on the `which_c... |
import re
import time
from pyquery import PyQuery as pq
from policy_crawl.common.fetch import get,post
from policy_crawl.common.save import save
from policy_crawl.common.logger import alllog,errorlog
def parse_detail(html,url):
alllog.logger.info("云南省教育厅: %s"%url)
doc=pq(html)
data={}
data["title"]=d... |
import pickle
import numpy as np
INF = np.inf
NO_PATH = - np.inf
NOT_MATCH = -1
NEAR_ZERO = 1e-12
class KM:
def __init__(self, graph):
# weight of each edge
self.graph = np.array(graph, dtype=float)
self.min_value = np.min(self.graph)
self.graph -= self.min_value
# self.... |
import numpy as np
import onnxruntime
import onnx
import tokenization
import os
from run_onnx_squad import *
import json
from run_onnx_squad import read_squad_examples, convert_examples_to_features, write_predictions
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import tqdm
from squad_eva... |
"""Module for making a key based on a master key, a salt, and a passphrase
"""
import dataclasses
import os
import pbkdf2
DEFAULT_ENTRY_KEY_SIZE = 256 // 8
DEFAULT_ENTRY_SALT_SIZE = 128 // 8
DEFAULT_SALT_SIZE = 64 // 8
@dataclasses.dataclass(frozen=True)
class KeyCipher:
"""Can generate a new key, and recreate a... |
#!/usr/bin/env python3
"""
Polyglot v2 node server for Russound control/status via RNET
Copyright (C) 2020 Robert Paauwe
"""
import sys
import time
try:
import polyinterface
except ImportError:
import pgc_interface as polyinterface
from nodes import russound
from nodes import zone
LOGGER = polyinterface.LOGGER... |
import os
import sys
import importlib
import logging
import argparse
from base64 import b64decode
import json
import requests
from uqcsbot.base import UQCSBot, bot, Command
SLACK_VERIFICATION_TOKEN = os.environ.get("SLACK_VERIFICATION_TOKEN", "")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN", "")
# UQCSTesting b... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# mountsnoop Trace mount() and umount syscalls.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: mountsnoop [-h]
#
# Copyright (c) 2016 Facebook, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 14-Oct-2016 Omar Sandoval Created ... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette_driver import By, Wait
from marionette_driver.errors import StaleElementException
from gaiatest import ... |
import cv2
import numpy as np
kernel = np.ones((5,5), np.uint8)
img = cv2.imread("resources/1591988497278.jpg")
print(img.shape)
edge_img = cv2.Canny(img, 30, 30)
resize_img = cv2.resize(img,(300, 200))
cropped_img = img[:200, :200]
cv2.imshow("image box", img)
cv2.imshow("edge image", edge_img)
cv2.imshow("resized ... |
import os
import sys
import traceback
from queue import Queue
from threading import Thread
from test_results_reader import read_results
from helpers import batch
from azure_devops_result_publisher import AzureDevOpsTestResultPublisher
class UploadWorker(Thread):
def __init__(self, queue, idx, collection_uri, tea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This is rumdom run node.
subscribe No topcs.
Publish 'cmd_vel' topic.
mainly use for simple sample program
by Takuya Yamaguhi.
'''
import rospy
import random
from geometry_msgs.msg import Twist
class RandomBot():
def __init__(self, bot_name="NoName"):
... |
import random
import copy
from typing import Dict
from UnleashClient import utils
from UnleashClient.constants import DISABLED_VARIATION
class Variants():
def __init__(self, variants_list: list, feature_name: str) -> None:
"""
Represents an A/B test
variants_list = From the strategy docum... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
#!/usr/bin/env python
"""Creates the pin file for the Teensy."""
from __future__ import print_function
import argparse
import sys
import csv
SUPPORTED_FN = {
'FTM' : ['CH0', 'CH1', 'CH2', 'CH3', 'CH4', 'CH5', 'CH6', 'CH7',
'QD_PHA', 'QD_PHB'],
'I2C' : ['SDA', 'SCL'],
'UART' : ['RX'... |
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 Maciej Wasilak <http://sixpinetrees.blogspot.com/>,
# 2013-2014 Christian Amsüss <c.amsuess@energyharvesting.at>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompany... |
import webbrowser
from googletrans import Translator
class Network:
@staticmethod
def Download(download_keyword):
webbrowser.open(f"https://store.steampowered.com/search/?term={download_keyword}")
@staticmethod
def Translate(word, when_lang):
translator = Translator()
return t... |
#
# The XBUILD depenceny generator.
#
# (c) 2012 The XTK Developers <dev@goXTK.com>
#
import os
import sys
import subprocess
import config
from _cdash import CDash
from _colors import Colors
from _jsfilefinder import JSFileFinder
#
#
#
class DepsGenerator( object ):
'''
'''
def run( self, options=None ):
... |
# -*- coding: utf-8 -*-
import math
from typing import Optional, Tuple
import warnings
import torch
from torch import Tensor
__all__ = [
"spectrogram",
"griffinlim",
"amplitude_to_DB",
"DB_to_amplitude",
"compute_deltas",
"compute_kaldi_pitch",
"create_fb_matrix",
"create_dct",
"c... |
#!/usr/bin/env python3
import os
import logging
import sys
import argparse
from binascii import hexlify
from struct import pack, unpack
from Library.usblib import usb_class
from Library.utils import LogBase
from Library.utils import print_progress
class Stage2(metaclass=LogBase):
def __init__(self, args, loglevel... |
"""
https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 ... |
import os
from django.http.response import Http404
import json
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.views import View
from django.conf import settings
from django.core.files.base import ContentFile
from wsgiref.util import FileWrapper
from pm4pymdl.objects.oce... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.c_like
~~~~~~~~~~~~~~~~~~~~~~
Lexers for other C-like languages.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, inherit,... |
'''
Created on Jul 18, 2019
The module contains one function.
The function needs two input parameters.
The first input parameter is a list.
The second input parameter is txt file operating.
The function is to handling the list and save the comments to txt file.
@author: ekexigu
'''
from re import sub as s
def creat... |
# Copyright (c) 2015 Microsoft Corporation
from z3 import *
set_option(relevancy=0,verbose=1)
def flatten(l):
return [s for t in l for s in t]
class TransitionSystem():
def __init__(self, initial, transitions, vars):
self.fp = Fixedpoint()
self.initial = initial
self.transitions = transitions
self... |
'''from parlai.core.agents import add_datapath_and_model_args, create_agent_from_opt_file
from parlai.core.build_data import modelzoo_path
from ..base.agents.base import Seq2SeqLM
from ..base.agents.parlai import ParlaiGenerationAgent
class RedditAgent(ParlaiGenerationAgent, Seq2SeqLM):
def __init__(self, model... |
import loguru
from bs4 import BeautifulSoup
from src.core import FilesHandler
from src.parsers.BaseParser import BaseParser
class JobParser(BaseParser):
def __int__(self, *args, **kwargs):
super(JobParser, self).__int__(*args, **kwargs)
loguru.logger.info("JOB PARSER INSTANTIATED")
def par... |
import abc
import asyncio
import logging
import typing as t
from collections import namedtuple
from functools import partial
import discord
from discord import Guild, HTTPException, Member, Message, Reaction, User
from discord.ext.commands import Context
from bot import constants
from bot.api import ResponseCodeError... |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import LmcoinTestFramework
from test_framework.util import *
import time
from ... |
#######################################################################################################################
# #
# Copyright (c) 2018 Qualcomm Technologies, Inc. ... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def loadFromFile(nameFile):
d = np.load('../data/'+nameFile+name+'array.npy')
print('Reading from' + '../data/'+nameFile+name+'array.npy')
return d
def diff(x, y, y2, name):
newY = abs(y - y2)
fig = plt.figure()
ax = plt.sub... |
import json
import os
import logging
import sys
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
from pyssdb import pyssdb
CONFIG_FILE = 0
ARGUMENT_LIST = [
[CONFIG_FILE, "-f", "<config_file_name>", True],
]
def PrintUsage():
print("\n", __file__, "\n")
for argItem in ... |
import sys, os
from multiprocessing import Process
import torch
from codes.a_config.parameters import PARAMETERS as params
import codes.f_main.federation_main.utils as utils
from rl_main import rl_utils
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if __name__ == "__main__":
utils.make_... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.xmatch`.
"""
url = _config.ConfigItem(
'http://cdsxmatch.u-strasbg.fr/xmatch/api/v1/sync',
'xMatch URL... |
from bitstring import BitStream, BitArray
from mido import MidiFile
import base64
def bitstring_to_bytes(s):
return bytes(int(s[i : i + 8], 2) for i in range(0, len(s), 8))
mid = MidiFile('output.mid')
i = 0
bitone = []
bittwo = []
notes = [50,52,53,55,57,59,60,62,64,65,67,69,71,72,74,76]
volume = [100,99,98,97,9... |
import sys
import warnings
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
install_requires = ['requests>=2.4.2']
if sys.version_info < (3, 4, 0):
install_requires.append('enum34')
if sys.version_info < (2, 7, 9):
warnings.warn(
'Users have reported iss... |
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import (VGG, xavier_init, constant_init, kaiming_init,
normal_init)
from mmcv.runner import load_checkpoint
from ..registry import BACKBONES
@BACKBONES.register_module
class SSDVGG(VGG):
extra_s... |
###############################################################################
##
## Copyright (C) 2014 Tavendo GmbH
##
## 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:/... |
# Your traffic light controller program has been patented, and you’re about to become seriously rich.
# But your new client needs a change.
# They want four states in their state machine:
# Green, then Green and Orange together, then Orange only, and then Red.
# Additionally, they want different times spent in each sta... |
# Licensed under the Upwork's API Terms of Use;
# you may not use this file except in compliance with the Terms.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or i... |
from ate import utils, exception
class ResponseObject(object):
def __init__(self, resp_obj):
""" initialize with a requests.Response object
@param (requests.Response instance) resp_obj
"""
self.resp_obj = resp_obj
self.success = True
def parsed_body(self):
try... |
"""
This is intended to be plug-and-play short squeeze analysis. Generates top picks and plots.
Need to add in earnings dates into the mix. Stocks with earnings coming up should be looked into more.
"""
import sys
import talib
import pandas as pd
import numpy as np
from tqdm import tqdm
from sklearn.ensemble import... |
def FillNan(df, method='linear'):
"""Fill Nan values of X_train of X_test with an interpolation."""
# Interpolate the missing value thanks to interpolation for each station_id
columns_to_interpolate = ["value_" + str(i) for i in range(10)]
# Group samples by station_id
g_stations_df = df.groupby([... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import hashlib
import json
import time
from werkzeug.exceptions import NotFound
import frappe
from frappe import _, msgprint, is_whitelisted
from frappe.utils import flt, cstr, now, get_datetime_str, file_lock, date_diff
f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
nome = str(input('Digite o seu nome: '))
i = int(input('Digite a sua idade: '))
p = float(input('Digite o seu peso: '))
a = float(input('Digite a sua altura: '))
imc = p/a**2
print(f"{'':=^20}")
print(f"{'Ficha IMC':^20}")
print(f"{'':=^20}")
print('Nome: {}'.format(nome))
print('Idade: {}'.format(i))
print('Peso: {}kg... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
#
# Copyright (C) 2014-2015 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Ben Dyer <ben_dyer@mac.com>
# Pavel Kirienko <pavel.kirienko@zubax.com>
#
"""
Python DroneCAN package.
Supported Python versions: 3.2+, 2.7.
"""
from __future__ i... |
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class SidebarmacrosPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
def get_settings_defaults(self):
return dict(
column = 1,
... |
# Copyright (c) 2022, Framras AS-Izmir and Contributors
# See license.txt
# import frappe
import unittest
class TestUBLTRDespatchAdvice(unittest.TestCase):
pass
|
from starlette.status import HTTP_200_OK, HTTP_403_FORBIDDEN
from starlite import RouteHandler, create_test_client, get
from starlite.exceptions import PermissionDeniedException
from starlite.request import Request
async def local_guard(_: Request, route_handler: RouteHandler) -> None:
if not route_handler.opt o... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from pynggdpp import ndc
import json
def cache_collection(event=None, context=None):
processable_collection = ndc.get_message("processable_collections")
if processable_collection is None:
response = {
"statusCode": 204
}
return response
else:
body = dict()
... |
#!/usr/bin/python
import os
import sys
import json
if sys.version_info[0] < 3:
import thread
else:
import _thread
import threading
class AbstractConnector():
def __init__(self, local_device):
self.Protocol = None
self.Adaptor = None
self.LocalDevice = local_device
# Flags
self.IsConnected = False
#... |
from typing import Any, Callable, List, Optional
import vpython
# There's a bit of magic here. Normally, vpython.wtext will make a
# <div> in the HTML and automaticall update it when the .text field is
# updated in this python code. But if you want to insert a wtext in the
# middle of a field, the following first att... |
# INSTRUCTIONS
# Translate the text and write it between the "
# EXAMPLE: original -> "This text is in english: value {0}"
# translation -> "Aquest text està en anglès: valor {0}"
# If you see sth like {0}, {1}, maintain it on the translated sentence
# Meke special attention to elements like "... |
MONEY_IN_THE_MACHINE = 0.0
CURRENT_USER_CHANGE = 0.0
COIN_TYPES = {
'quarters': .25,
'dimes': .1,
'nickles': .05,
'pennies': .01
}
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-plot/ampel-plot-browse/ampel/plot/T2SVGQuery.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 15.06.2019
# Last Modified Date: 19.11.2021
# Last Modified By: v... |
import requests
model_id = 'Enter-your-model-id'
api_key = 'Enter-your-api-key'
image_path = 'path/to/your/image'
url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/' + model_id + '/LabelFile/'
data = {'file': open(image_path, 'rb'), 'modelId': ('', model_id)}
response = requests.post(url, auth=request... |
import tensorflow as tf
import numpy as np
import Constants as Constants
from Log import log
from Util import average_gradients, clip_gradients
class Trainer(object):
def __init__(self, config, train_network, test_network, global_step, session):
self.profile = config.bool("profile", False)
self.a... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# This program is distrib... |
"""
Django settings for Main project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
imp... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... |
# -*- coding: utf-8 -*-
"""HEART_DISEASE_PREDICTION.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1yc00bQ4VnOoHkCp3NaMbUnL2qCZmz_Xk
***HEART DISESE PREDICTION PROJECT***
**IMPORTING LIBRARIES AND UPLOADING DATA SET**
"""
import numpy as np
im... |
# Generated by Django 2.0.6 on 2018-11-05 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0035_auto_20181105_1650'),
]
operations = [
migrations.AlterField(
model_name='representatives',
name='re... |
#data types and expressions
#combining booleans with either and / or
x = 5
y = 6
print("x:", x, "y:", y)
#Test equals == and not equals !=
print("Is x equal to y and is x != y? : ", x == y and x != y) #returns False
#Test equals == or not equals !=
print("Is x equal to y or x is not equals y? : ", x == y or x != y)... |
def select_columns(selected, numeric_features, categorical_features, RMR_type='MIQ', n_clusters=6, cols=20):
"""
Scale data, geneate categorcal columns
and create Kmeans model
args:
selected: selected dataframe
numeric_features: numeric column names
categorical_features: :... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Borealis Systems and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class Village(Document):
pass
|
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
# -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
from django.conf import settings
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Trek.source'
db.delete_column('o_t_itineraire', 'source')
# Addi... |
# Copyright (c) 2019-2020, NVIDIA 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import os
import sys
from RLTest import Env
from redisgraph import Graph, Node, Edge
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from base import FlowTestsBase
graph = None
redis_con = None
people = ["Roi", "Alon", "Ailon", "Boaz"]
class testResultSetFlow(FlowTestsBase):
def __init__(self):... |
from . import *
import dj_database_url
DEBUG = ENV("DEBUG", "0") == "1"
DEBUG_TOOLBAR = DEBUG
INSTALLED_APPS += []
try:
DATABASES['default'] = dj_database_url.parse(
os.environ.get('DATABASE_URL'))
DATABASES['default']['ENGINE'] = os.environ.get(
'DB_ENGINE', 'django.db.backends.postgresql_p... |
from datetime import date
atual = date.today().year
ano = int(input('Ano de nascimeto: '))
idade = atual - ano
print('O atleta tem {} anos'.format(idade))
if idade <= 9:
print('CLASSIFICAÇÃO: MIRIM')
elif idade <= 14:
print('CLASSIFICAÇÃO: INFANTIL')
elif idade <= 19:
print('CLASSIFICAÇÃO: JUNIOR')
elif ida... |
import pdb
import copy
import pytest
import threading
import datetime
import logging
from time import sleep
from multiprocessing import Process
import sklearn.preprocessing
from milvus import IndexType, MetricType
from utils import *
dim = 128
index_file_size = 10
table_id = "test_mix"
add_interval_time = 2
vectors = ... |
"""core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'text_to_qr.ui',
# licensing of 'text_to_qr.ui' applies.
#
# Created: Fri Jul 17 14:35:18 2020
# by: pyside2-uic running on PySide2 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, Q... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-31 21:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/python
#
# cab.py: Create Aiken Biphase
# create a WAV file with arbitrary data in it
#
# Copyright(c) 2006, Major Malfunction <majormal@pirate-radio.org>
# http://www.alcrypto.co.uk
#
# inspired by 'dab.c' by Joseph Battaglia <sephail@sephail.net>
#
# Permission is hereby granted, free of charge, to any p... |
class GridDefinition(object):
SAMPLE_INDEX = 0
TRACE_INDEX = 1
FRAME_INDEX = 2
VOLUME_INDEX = 3
HYPERCUBE_INDEX = 4
SHOT = 0
CDP = 1
OFFSET = 2
VOLUME = 3
def __init__(self):
pass
|
# Copyright 2019 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
import unittest
from os.path import join
from tests import TestCase, FILES_DIR
from modipyd.tools import generic
class GenericToolTestCase(TestCase):
def parse_options(self, args):
parser = generic.make_option_parser()
self.assertNotNone(parser)
return parser.parse_... |
# ===================================================================
#
# Copyright (c) 2018, Helder Eijs <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistribut... |
import matplotlib.pyplot as plt
import pymc3 as pm
from scipy.special import logit, expit
from scipy.stats import gaussian_kde, laplace, norm
import numpy as np
plt.style.use('seaborn')
filenames = ['label_correlation', 'hpo_implicit_als', 'hpo_implicit_bpr',
'hpo_lightfm_warp', 'hpo_lightfm_warp_fp', '... |
#!/usr/bin/env python3
# Code credit to PyMoTW3
# This is not an exact copy, and was only used as a
# study aid in the process of understanding `smtplib`
# and its use.
import sys
import smtplib
import email.utils
import getpass
from email.mime.text import MIMEText
recipient = input("Recipient address: ")
server_nam... |
import numpy as np
def l2_regularization(W, reg_strength):
'''
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gra... |
import urllib.request
import random
from bs4 import BeautifulSoup
from requests import get
import mysql.connector
conn = mysql.connector.connect(user="root", passwd="",host="localhost", database="product")
cursor = conn.cursor()
sql = """INSERT INTO drymoistd (about, rate, top, comment, dari) VALUES (%s, %s, %s, %s,... |
import json
import logging
import time
import ccxt
from ccxt.base.errors import (
BaseError,
InsufficientFunds,
OrderNotFound,
NetworkError)
from decimal import Decimal as D
log = logging.getLogger(__name__)
def handle_errors(f):
def wrapper(*args, **kwargs):
r = {'type... |
# coding: utf8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
# The MIT License (MIT)
#
# Copyright (c) 2019 Scott Shawcroft for Adafruit Industries LLC
#
# 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 limit... |
# -*- coding:utf-8 -*-
import io
import uuid
from typing import List
from logging import getLogger
from fastapi import APIRouter, Depends, File, UploadFile
from starlette.requests import Request
from app.models.prediction import PredictionResult
from app.core import security
from app.services.models import ImageClass... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^logout$', views.logout, name='logout'),
url(r'^resources/$', views.get_resources, name='resources'),
url(r'^puzzles/$', views.get_puzzles, name='get'),
url(r'^webhook/$', views.update... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
import sys, os
class IxLoadRobot(object):
"""Library for IxLoad Robot API.
= Table of contents =
- `Prerequisites`
- `Samples`
- `Importing`
- `Shortcuts`
- `Keywords`
= Prerequisites =
In order to be able to run Robot API scripts, Ixload must be installed with th... |
from datetime import datetime
import threading as th
import time, logging, importlib, os, time
import inspect
import os
import sqlite3
class CalibrationMaster():
# Parent class for all the calibration classes.
def __init__(self):
# init values: set in such a way they will not result in a function call... |
#
# Copyright 2022 The AI Flow 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 w... |
from twocode.parser import Console as ConsoleBase
import sys
import twocode.utils.code
class Console(ConsoleBase):
def __init__(self, context=None):
super().__init__()
from twocode import Twocode
if context is None: context = Twocode()
self.twocode = context
self.c... |
from ....Classes.Segment import Segment
from ....Classes.Arc1 import Arc1
from ....Classes.Arc3 import Arc3
def _comp_line_dict(self):
"""Define a dictionnary of the lines to draw the slot
If a line has begin==end, it is replaced by "None" (dict has always the same number of keys)
Parameters
--------... |
import cv2
import time
import pandas
from datetime import datetime
import numpy as np
first_frame = None
status_list = [None, None]
times = []
df = pandas.DataFrame(columns=["Start", "End"])
video = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVI... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.