content stringlengths 5 1.05M |
|---|
import numpy as np
from matplotlib import pyplot as plt
import pickle
def plot(title, xlabel, ylabel, X_list, Y_list, L_list, save_file):
plt.figure(figsize=(12,8))
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
legend_tup = []
legend_label = []
for i in range(len(X_list)):
l, = plt.plot(X_list[i], Y_... |
#!/usr/bin/env python
# coding=utf-8
import os
import click
import csv
from collections import defaultdict
@click.command("find_gene", help="According to the results of GWAS, the genes of upstream and downstream 1M of SNP locus were selected.")
@click.option(
"-g", "--gff", type=str, help="gff file (It can only c... |
from email.encoders import encode_base64
import unittest
from mox3.mox import MoxTestBase, IsA
from gevent.socket import socket, error as socket_error
from gevent.event import AsyncResult
from slimta.util import pycompat
from slimta.util.deque import BlockingDeque
from slimta.smtp import ConnectionLost
from slimta.re... |
"""
Copyright (c) 2016-17 Keith Sterling http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, mod... |
from django.db import models
from Profile.models import *
from django.contrib.auth.models import User
class Appointments(models.Model):
patient = models.ForeignKey(User_detail,on_delete= models.CASCADE)
doctor = models.ForeignKey(Doctor_details,on_delete=models.CASCADE,null = True)
date = models.DateFie... |
from cerebrum.language.analysis import *
|
# Generated by Django 3.1.7 on 2021-03-13 20:44
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
field... |
from __future__ import unicode_literals
from slugify import slugify
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
try:
from django.utils.encoding import force_text
except ImportError: # pragma: no cover
from django.utils.encoding import force_unicode as force_text
f... |
import pytest
import logging
from dtest import RUN_STATIC_UPGRADE_MATRIX, Tester
from distutils.version import LooseVersion
from tools.misc import add_skip
from .upgrade_manifest import build_upgrade_pairs
since = pytest.mark.since
logger = logging.getLogger(__name__)
@pytest.mark.upgrade_test
class UpgradeUDTFixTes... |
import discord
import util
from emoji import clean_emoji
class District:
def __init__(self, bot, cat_id, role_id, station_id, stations, trains):
self.bot = bot # discord.CLient
self.cat_id = cat_id # Snowflake
self.role_id = role_id # Snowflake
self.station_id = station_id # S... |
# Copyright 2021 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 to in wr... |
from flask import render_template
from flask.views import View
class WebResource(View):
def dispatch_request(self):
title = "UMA OCR"
return render_template('index.html', title=title)
|
# Copyright 2015 NEC Corporation. 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 ... |
import os
import torch
from torch import optim
from torch.optim.lr_scheduler import StepLR
from torch import nn
from torch.nn import functional as F
from tvae.data.mnist import DualTransformPreprocessor
from tvae.containers.tvae import TVAE
from tvae.models.mlp import MLP_Encoder, MLP_Decoder
from tvae.containers.enco... |
"""
Common functions for use in graph generation
"""
import itertools
import sys
from functools import partial
from typing import Optional, Dict, Any
try:
from fmt.fmt import Parser, Expression, Constant, generate
except ImportError as err:
raise RuntimeError(
"`fmt` must be installed to use the statey... |
# coding: utf-8
from onnx import helper
from ch2o.callable import Callable
from ch2o.funcs import Func, totensor
from ch2o.utils import istensor, new_tensor
class Builtin_Len(Callable):
def __init__(self):
super(Builtin_Len, self).__init__(lambda x: x)
def call_impl(self, env, x):
x = x.to_... |
"""
Contains the PostQuery class
"""
from e621apy import Query, helpers
__all__ = [
'PostQuery',
]
class PostQuery(Query):
"""
Query designed to match Posts data
"""
RATING_SAFE = 'safe'
RATING_QUESTIONABLE = 'questionable'
RATING_EXPLICIT = 'explicit'
RATING_ALL = 'all'
def __i... |
from vector_tile_base import *
import os
import sys
# To create a new test fixture create a method
# that starts with "create_" and returns a string
# of a vector tile buffer. This will be saved to a
# file in the test/data/ folder using the name of
# the method provided. The next name after "create_"
# can be be "val... |
#v2.1.0
#https://github.com/romanvm/script.module.simpleplugin/releases
from .simpleplugin import *
|
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
def calculateAfter(days = 500, file = 'data/full_grouped.csv'):
df=pd.read_csv('data/full_grouped.csv', sep=',',names=['Date','Country/Region','Confirmed','Deaths','Recovered','Active','New cases','New deaths','New recovered... |
# pylint: disable=redefined-outer-name
import pytest
import slash
from io import StringIO
from slash.frontend.slash_run import slash_run
def test_errors_during_initialization_hoook(suite, init_hook):
@init_hook.register
def callback(): # pylint: disable=unused-variable
raise slash.exceptions.SlashE... |
"""
This module provides the asyncio client for Cisco NX-API, expected to work on:
* N3K system
* N5K system (tested)
* N7K system
* N9K system
"""
from typing import Optional, List, AnyStr
import json
from socket import getservbyname
import httpx
import ssl
from asyncnxapi import xmlhelp
__all__ =... |
import cirq
# from numpy.testing._private.utils import clear_and_catch_warnings
import numpy as np
# import tensorflow as tf
# import matplotlib.pyplot as plt
print("\n\n-------------------—Beginning of Program-------------------—")
def gate1(measure = True):
description = "Example of Hadamard gate acting on one ... |
"""
LC 215
Given an unsorted array of numbers, find Kth smallest number in it.
Please note that it is the Kth smallest number in the sorted order, not the Kth distinct element.
Note: For a detailed discussion about different approaches to solve this problem, take a look at Kth Smallest Number.
Example 1:
Input: [1, 5, ... |
"""
MPI-wrapper for executing pickled CNSJobs created by libmpi.
This was developed for use of lbimpi but it might be useful in some specific
scenario as a cli.
For more information please refer to the README.md in the examples folder.
Usage:
haddock3-mpitask -h
haddock3-mpitask tasks.pkl
"""
import argpar... |
from gameApi import GameChecker
#board = GameChecker('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1')
#
#list_move = board.showMove(8)
#print(board.board)
#
#make = board.makeMoveAPI(8, 16)
#print(make.isMoveValid)
#print(make.isKingCheck)
#print(make.isGameOver)
#print(make.fen)
#for i in range(len(list_... |
# Copyright (C) 2015-2021 Virgil Security, Inc.
#
# 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) Redistributions of source code must retain the above copyright
# notice, this li... |
import os
import sys
import csv
import json
import shutil
import requests
from ..config import Config
RPC_URL = 'http://localhost:6800/jsonrpc'
FASTA_DIR = os.path.join(Config.ROOT_DIR, 'fastas')
GFF_DIR = os.path.join(Config.ROOT_DIR, 'gffs')
INFO_DIR = os.path.join(Config.ROOT_DIR, 'info')
ASSEMBLY_REPORT_DIR = os.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 6 12:59:13 2017
@author: aantoniadis
"""
import argparse
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from PyAstronomy import pyasl
plt.rcParams['xtick.direction'] = 'in'
pl... |
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
# Python 3 implementation of the algorithms in Chapter 3 of the book
# "Algorithms Unlocked" by Thomas H. Cormen.
#
# MIT License
#
# Copyright (c) 2019 Joshua Nunn
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... |
"""illumidesk version info"""
# for now, update the version so that its the same as the one reflected
# within the repo's root package.json
version_info = (
0,
10,
0,
)
__version__ = ".".join(map(str, version_info[:3]))
if len(version_info) > 3:
__version__ = "%s%s" % (__version__, version_info[3])
|
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import board
from adafruit_turtle import turtle
def hilbert2(step, rule, angle, depth, t):
if depth > 0:
a = lambda: hilbert2(step, "a", angle, depth - 1, t)
b = lambda: hilbert2(step, "b", ang... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-09-20 18:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0029_auto_20170914_1954'),
]
operations = [
migrations.AddField(
... |
import sys
import requests
import json
from veracode_api_signing.plugin_requests import RequestsAuthPluginVeracodeHMAC
#JSON
api_base = "https://api.veracode.com/appsec/v2"
headers = {"User-Agent": "Python HMAC",'content-type': 'application/json'}
if __name__ == "__main__":
try:
response = requests.get(a... |
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from i... |
# (C) Copyright 2020-2021 UCAR
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
import os
import yamltools
import ewok.tasks.getInitialConditions as generic
class getInitialConditionsGFS(generic.getInitialConditions... |
import pylife
pylife.main() |
import os, sys
#Calculate the path based on the location of the WSGI script.
apache_configuration= os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace)
os.environ['DJANGO_SETTINGS_MODULE'] = 'localground.apps.settings'
#import djang... |
class MultiDBRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'girlstatue':
return 'girlstatue_db'
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'girlstatue':
return 'girlstatue_db'
... |
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, auth, Group
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts ... |
from django.shortcuts import render
from rest_framework import generics
from User.models import User
from User.serialize import UserSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from User.filter import UserFilter
class UserList(generics.ListCreateAPIView):
... |
"""
Modified tensorrt inference server image client sample
From : https://gist.github.com/CasiaFan/8206610cd027bd130071220870a1f89c
"""
import argparse
import numpy as np
import os, time
import tensorrtserver.api as tapi
import tensorrtserver.api.model_config_pb2 as model_config
import cv2
from functools import partia... |
from typing import NamedTuple
from ochs.utils import log
from ochs.utils.fs import write
class Page(NamedTuple):
url: str
content: str
def write(self, target_dir: str) -> None:
log.info(f"Writing '{self.url}'.")
write(f"{target_dir}/{self.url}", self.content)
|
#!/usr/bin/python
# -*- encoding: utf-8 -*-
#
# https://github.com/tripleee/entro.py
"""
Simple command-line calculator for variations of Shannon entropy
Try entro.py --help to see a list of options.
"""
import math, sys
from optparse import OptionParser # ugh
class Str (str):
def width (self, member):
... |
from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
class EventDispatcher(object):
__metaclass__ = ABCMeta
@abstractmethod
def observe(self, event_pattern, priority, callback):
"""
Register a callback to be invoked when a given event occurs. `observe`
... |
import streamlit as __st
import streambook
__toc = streambook.TOCSidebar()
__toc._add(streambook.H1('Streambook example'))
__toc._add(streambook.H2('Main Code'))
__toc._add(streambook.H2('Advanced Features'))
__toc._add(streambook.H2('Longer example'))
__toc._add(streambook.H2('Exporting to Jupyter'))
__toc.generate(... |
import pytest
def pytest_addoption(parser):
parser.addoption(
"--hitl", action="store_true", default=False, help="Human/Hardware in the Loop"
)
def pytest_collection_modifyitems(config, items):
if config.getoption("--hitl"):
return
skip_hitl = pytest.mark.skip(reason="Human/Hardware in... |
import torch
import os
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
masks = torch.load(sys.argv[1])
mask_tensors = [masks["tar"], masks["in"]]
for mask, save_root in zip(mask_tensors, ["style/", "content/"]):
if not os.path.exists(save_root):
os.makedirs(save_root)
... |
from datetime import datetime
from pydantic import BaseModel, AnyHttpUrl
# import uuid
class Action(BaseModel):
# id: str = Field(default_factory=uuid.uuid4)
type: str
set_status: str
comment: str
reporter: str
elog: AnyHttpUrl
date: datetime
class Config:
schema_extra = {
... |
from .sbmlplot import *
|
from tqdm.auto import tqdm
from joblib import Parallel
class ProgressParallel(Parallel):
"""A helper class for adding tqdm progressbar to the joblib library."""
def __init__(self, use_tqdm=True, total=None, *args, **kwargs):
self._use_tqdm = use_tqdm
self._total = total
super().__init_... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.prune as prune
import warnings
warnings.simplefilter("ignore")
from a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from a2c_ppo_acktr.utils import init
class Flatten(nn.Module):
d... |
# Copyright 2011 Denali Systems, Inc.
# 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 requ... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipI... |
import batoid
from test_helpers import timer
import numpy as np
@timer
def test_normalized():
for _ in range(1000):
x = np.random.uniform()
y = np.random.uniform()
z = np.random.uniform()
w = np.random.uniform()
np.testing.assert_allclose(
np.linalg.norm(batoi... |
# SPDX-License-Identifier: MIT
import struct
from collections import defaultdict, deque
from enum import IntEnum
from ..trace.asc import ASCRegs
from ..utils import *
class BootRomMsg(IntEnum):
GET_STATUS = 2
BOOT_TZ0 = 5
BOOT_IMG4 = 6
SET_SHMEM = 0x18
class BootRomStatus(IntEnum):
STATUS_OK = ... |
import typing as typ
from mypy_extensions import TypedDict
Cell = TypedDict("Cell", {"code": typ.Text, "cell_id": typ.Text})
MIME = typ.Text
Metadata = typ.Dict[MIME, typ.Dict[typ.Text, typ.Any]]
MIMECode = typ.Dict[MIME, typ.List[Cell]]
Request = TypedDict(
"Request",
{"request_id": int, "cell_id": typ.T... |
import json
import logging
import struct
import sys
import time
import traceback
from xml.dom import minidom
import requests
import event
from action import ActionNotifystate, ActionStatechange
from Crypto.Cipher import AES
from device import Device
from transport import TCPClient
from util import b2s,... |
#
# Copyright (c) 2020 Xilinx, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
import pytest
from roast.serial import Serial
from roast.utils import register_plugin
config = {
"board_interface": "host_target",
"remote_host": "remote_host",
"hostname": "hostname",
"com": "com",
"baudrat... |
matrix=[[0,1,1,2],[0,5,0,0],[2,0,3,3]]
s=0
for r in range(0,len(matrix)-1):
for c in range(0,len(matrix[r])):
if matrix[r][c]==0 and matrix[r+1][c]!=0:
s=s+0
else:
s=s+matrix[r][c]
print(s)
|
import pyupm_i2clcd as lcd
# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS)
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
myLcd.setCursor(0,0)
# RGB Blue
#myLcd.setColor(53, 39, 249)
# RGB Red
myLcd.setColor(255, 0, 0)
while(True):
myLcd.write('Hello World')
myLcd.setCursor(1,2)
myLcd... |
from flopz.arch.ppc.vle.instructions import *
def test_arithmetic():
add = SeAdd(4, 0) # se_add r4, r0
assert(add.opcode.uint == 0x1)
assert(add.RY().uint == 0)
assert(add.RX().uint == 4)
# it should encode
assert(add.bytes() == b'\x04\x04')
# 06 35 se_sub r5,r3
sub = S... |
"""update controle_mutation
Revision ID: 595d5ae348fd
Revises: 562661974c46
Create Date: 2022-01-18 09:06:59.972943
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '595d5ae348fd'
down_revision = '562661974c46'
branch_labels = None
depends_on = None
def upgrade... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
import torch.fx
from torch.testing import FileCheck # @ma... |
##file = open("test.txt",'wb')
##file.seek(1024*1024)
##file.write(b'\x00')
##file.close()
file = open("bitfield", 'wb')
#for i in range(0,64,2):
# file.seek(16384*i, 0)
file.write(b'\xff'*17995)
file.close()
|
import os
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QObject, pyqtSignal
from PyQt4.QtGui import *
import settings
class ThumbnailItem(QtGui.QLabel):
"""Represents an Elemement within a view, contains an Image and TextFields"""
signalItemDragged = pyqtSignal(str, name='itemDragged')
#menu = ... |
import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
from RecoBTag.Skimming.btagMC_QCD_120_170_EventContent_cff import *
btagMC_QCD_120_170OutputModule = cms.OutputModule("PoolOutputModule",
btagMC_QCD_120_170EventSelection,
FEVTSIMEventContent,
dataset = cms.u... |
from yagwip.gromacs_sim import GromacsSim, correct_folder
import os
from shutil import copyfile, copytree, rmtree
import glob
import re
class Experiment:
""" An Experiment is a group of GROMACS simulations run with identical conditions.
"""
def __init__(self, pdb_file_list, maindir, basefilesdir, jobdir,... |
import os
from math import isclose
from Jumpscale import j
"""
j.sal.ubuntu._test(name='ubuntu')
"""
j.sal.process.execute("apt update -y")
try:
j.sal.process.execute("apt-get install -y python3-distutils-extra python3-dbus python3-apt")
except:
j.sal.process.execute("apt-get install -y python3-dbus python3-... |
import serial
import time
import struct
toneIndex=0
def setup(dev): #dev example '/dev/ttyUSB0'
print("roomba setup")
global ser
ser = serial.Serial(dev, 115200)
# ser.write('\x80');
ser.write(bytes([0x80]));
time.sleep(0.4);
ser.write(bytes([0x83]));
# ser.write('\x83');
time.sleep(... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
class AttentiveSqueezeLayer(nn.Module):
"""
Attentive squeeze layer consisting of a global self-attention layer followed by a feed-forward MLP
"""
def __init__(self, in_channels, out_channels, k... |
import re
data = input()
pattern = r"^>>(?P<furniture_name>[a-zA-Z]+)<<(?P<price>\d+(\.\d+)?)!(?P<quantity>\d+)$"
furniture = []
total_money = 0
while data != "Purchase":
for el in re.finditer(pattern, data):
my_dict = el.groupdict()
furniture.append(my_dict['furniture_name'])
total_money ... |
#===================================================
#Title : Decision Tree Classifier for classifying a type of fruit
#Author : Amol Patil
#
#=======================================
#classes - Apple and Orange
#Features = [weight, texture]
#Texture- Smooth =1
# Bumpy =0
#Labels - Apple =0
# ... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint, TrafficLightArray
from std_msgs.msg import Int32
import copy
import numpy as np
import math
from scipy.spatial import KDTree
from geometry_msgs.msg import TwistStamped
"""
This node will publish wayp... |
from __future__ import print_function
import ais.stream
import ais
import ais.compatibility.gpsd
import datetime
import json
import sys
class NmeaMessage(object):
def __init__(self, raw, source="unknown"):
self.source = source
self.raw = raw
self.tagblock = {}
self.parse(self.raw)
... |
import warnings
warnings.filterwarnings('ignore', module='skimage')
from skimage.transform import resize
from . import pipeline
from . import transformations
from .pipeline import *
from .transformations import *
|
import requests, json, time
from .. import constants
from . import MondayApiError
def execute_query(api_key: str, timeout=constants.TIMEOUT, **kwargs):
"""Executes a graphql query via Rest.
__________
Parameters
__________
api_key : `str`
The monday.com API v2 user key.
timeout :... |
import prompt_toolkit.application as ptk_app
import prompt_toolkit.formatted_text as ptk_formatted_text
import prompt_toolkit.layout.containers as ptk_containers
import prompt_toolkit.layout.controls as ptk_controls
import prompt_toolkit.layout.layout as ptk_layout
from pygments.token import Token as T
from .multi im... |
from flask import Flask, request, jsonify
from flask_cors import CORS
from scipy.misc import imsave, imread, imresize
import numpy as np
import keras.models
import sys, os
sys.path.append(os.path.abspath('./model'))
import load as load_model
global model, graph
model, graph = load_model.init()
app = Flask(__name__,... |
## This code is written by Davide Albanese, <albanese@fbk.eu>.
## (C) 2010 mlpy Developers.
## 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 op... |
from job_search.application.services.jobs.job_factory import JobFactory
from job_search.domain.jobs.job_repository import JobRepository
from job_search.domain.jobs.job_source import JobSource
from job_search.domain.jobs.value_objects.job_type import JobTypeSource
class JobScrapingService:
def __init__(self, fact... |
'''
Forms for Raffle Prizes.
Created on Nov 1, 2012
@author: Cam Moore
'''
from django import forms
from apps.managers.challenge_mgr.models import RoundSetting
class ChangeRoundForm(forms.Form):
"""change round form."""
round_choice = forms.ModelChoiceField(queryset=RoundSetting.objects.all(), required=True... |
import cv2
import tensorflow as tf
import numpy as np
OUTPUT_PATH = "../events/"
NUM_FILTERS = 10
FILTER_SIZE = (3, 3)
STRIDES = (1, 1)
def nn(input_node):
with tf.variable_scope('nn'):
w = tf.get_variable(
name='weight',
shape=[FILTER_SIZE[0], FILTER_SIZE[1], 3, NUM_FILTERS],
... |
import json
import brownie
import pytest
from brownie import *
from config.badger_config import badger_config
from dotmap import DotMap
from helpers.constants import *
from helpers.gnosis_safe import GnosisSafe, multisig_success
from helpers.proxy_utils import deploy_proxy, deploy_proxy_uninitialized
from rich.console... |
# coding: utf-8
"""
PowerMeter API
API # noqa: E501
The version of the OpenAPI document: 2021.4.1
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from powermeter_api.configuration import Configuration
class Package(object):
"""NOTE: This cl... |
import platform
import subprocess
from . import common
from .error import UndevelopmentSubcommand
from .utils import (
order_filter,
find_task_locals_by_thread,
TaskEnv,
check_connect_sender,
)
# 目前要根据 defaults.VREDIS_COMMAND_TYPES 里面的参数进行开发各自的执行指令的方式
# 装饰器,用以过滤执行的任务。与 defaults 中的 VREDIS_FILTER_TASK... |
from authorize.apis.base_api import BaseAPI
from authorize.schemas import CreateRecurringSchema
from authorize.schemas import UpdateRecurringSchema
from authorize.schemas import ListRecurringSchema
from authorize.xml_data import *
class RecurringAPI(BaseAPI):
def create(self, params={}):
subscription = s... |
import cv2
print(cv2.__version__)
import dlib
print(dlib.__version__)
import matplotlib.pyplot as plt
imagem = cv2.imread("imagens/px-people.jpg")
imagem = cv2.cvtColor(imagem, cv2.COLOR_BGR2RGB)
plt.imshow(imagem)
imagem_gray = cv2.cvtColor(imagem, cv2.COLOR_RGB2GRAY)
classificador = cv2.CascadeClassifier("classifica... |
import pytest
from pybit.bits import Bits, BitsOperationError, BitsConstructError
def test_zero_construct():
empty = Bits(size=32)
assert empty == Bits([0 for x in range(32)])
assert len(empty) == 32
def test_bits_construct_eq():
one1 = Bits([0, 0, 0, 1], size=4)
one2 = Bits([0, 0, 0, 1], size=8)... |
#!/usr/bin/env python
""" Interact with Extreme Networks devices running EXOS """
import unittest
import mock
from pyEXOS import EXOS
from pyEXOS.exceptions import EXOSException
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException
class TestEXOS... |
# -*- coding: utf-8 -*-
"""Contains test for the lspi learn method."""
from unittest import TestCase
import lspi
from lspi.solvers import Solver
from lspi.policy import Policy
from lspi.basis_functions import FakeBasis
import numpy as np
class SolverStub(Solver):
def __init__(self, max_iterations):
self.m... |
# -*- encoding=utf8 -*-
import numpy as np
import copy
import os
import pickle
DEBUG = 0
STEP = 12
FIC = 1
def avg_mv(mv_full, xmin, ymin, xmax, ymax):
# mv_full is a tensor of H x W x 2
xmax = int(xmax)
ymax = int(ymax)
xmin = int(xmin)
ymin = int(ymin)
selected_area_x = mv_full[ymin:ymax, x... |
'''Made by Jackson Bremen ||| Written Summer 2018, Refactored Winter 2020
Trie Datastructure used from github below, additional functionality added
https://www.wordplays.com/boggle has line crossing be legal
'''
import readline
from Trie import Trie
dictionary = Trie()
with open('allScrabbleWords.txt', 'r') as file:
... |
from flask_restful import Resource
from flask import send_from_directory
from file import DIRETORIO_DOWNLOAD
from flask_jwt_extended import jwt_required
class Download(Resource):
@jwt_required()
def get(self, nome_arquivo):
return send_from_directory(DIRETORIO_DOWNLOAD, nome_arquivo, as_attachme... |
for num in range(7, 1001, 10):
print(num) |
from setuptools import find_packages, setup
version='0.1.2'
try:
long_description = open("README.txt").read()
except:
long_description = ''
try:
long_description += open("CHANGES.txt").read()
except:
pass
setup(name='trac-UserPicturesPlugin',
version=version,
description="Adds user pictur... |
class ServiceUnavailable(Exception):
pass
|
# coding:utf8
import sys
import os
from minio import Minio
from minio.error import ResponseError
minioClient = Minio('192.168.31.62:9000',
access_key='QUA2IU17RHOKE6NUZ7T2',
secret_key='MQniMc5K3lsRbv9OPaUbJN9ft2eTQJ1rh4Yx6C17',
secure=False)
if not minio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.