content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from datetime import date
nascimento = int(input('qual o ano do seu nascimento: '))
anoatual = date.today().year
idade = anoatual - nascimento
if idade <= 9:
print('VocÊ tem {} anos, sua categoria é Mirim'.format(idade))
elif idade <= 14 and idade > 9:
print('Você tem {} anos, sua categoria é Infantil'.format(i... | python |
# coding=utf-8
class Human(object):
def __init__(self, input_gender):
self.gender = input_gender
def printGender(self):
print self.gender
li_lei = Human('male') # 这里,'male'作为参数传递给__init__()方法的input_gender变量。
print li_lei.gender #这一行结果与下一行对比
li_lei.printGender() #这一行结果与上一行对比 | python |
from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import show_cam_on_image
from torchvision.models import resnet50
import torch
model = resnet50(pretrained=... | python |
#!/usr/bin/env python3
from email.message import EmailMessage
import smtplib, ssl
import getpass
message = EmailMessage()
sender = "me@example.com"
recipient = "youw@example.com"
message['From'] = sender
message['To'] = recipient
message['Subject'] = 'Greetings from {} to {}!'.format(sender, recipient)
body = """H... | python |
# Copyright 2020 The TensorFlow Probability 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 o... | python |
import os
import sys
import math import json
import numpy as np
from pycocotools.coco import COCO
import pickle
sys.path.insert(0,'..' )
from config import cfg
COCO_TO_OURS = [0, 15, 14, 17, 16, 5, 2, 6, 3, 7, 4, 11, 8, 12, 9, 13, 10]
def processing(ann_path, filelist_path, masklist_path, json_path, mask_dir):
... | python |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
SPEC = {
'settings': {
'build_gs_bucket': 'chromium-v8',
# WARNING: src-side runtest.py is only tested with chromium CQ builders.
# Usage not c... | python |
# Copyright (c) 2015 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... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import rosunit
from mock import patch
from parameterized import parameterized, param
from fiware_ros_bridge.logging import getLogger
class TestGetLogger(unittest.TestCase):
@parameterized.expand([
param(logm='debugf', rosm='logd... | python |
from sims4.tuning.tunable import HasTunableSingletonFactory, AutoFactoryInit, OptionalTunable, TunableVariant
from ui.ui_dialog import UiDialogOk, UiDialogOkCancel
import enum
import services
class SituationTravelRequestType(enum.Int):
ALLOW = ...
CAREER_EVENT = ...
DISALLOW = ...
class _SituationTravelRe... | python |
"""
Intersecting Linked Lists
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
In this example, assume nodes with the same value are the exact same node objects.
Input: 3 -> 7 -> 8 -> 10, 99 -> 1 -> 8 -> 10
Output: 8
=================================... | python |
from setuptools import setup
from torch.utils.cpp_extension import CUDAExtension, BuildExtension
setup(name='syncbn_gpu',
ext_modules=[CUDAExtension('syncbn_gpu', ['syncbn_cuda.cpp', 'syncbn_cuda_kernel.cu'])],
cmdclass={'build_ext': BuildExtension}) | python |
# -*- coding: utf-8 -*-
class MetadataError(Exception):
pass
class CopyError(RuntimeError):
pass
def err_contains_group(path):
raise ValueError('path %r contains a group' % path)
def err_contains_array(path):
raise ValueError('path %r contains an array' % path)
def err_array_not_found(path):
... | python |
#Write a function to swap a number in place( that is, without temporary variables)
#Hint 491: Try picturing the two numbers, a and b, on a number
#Hint 715: Lef diff be the difference betweeen a and b. Can you use diff some way? Then can you get rid of this temporary variable.
#Hint 736: You could also try to using XO... | python |
msg = ['We see immediately that one needs little information to begin to break down the process.','An enciphering-deciphering machine (in general outline) of my invention has been sent to your organization.','The significance of this general conjecture, assuming its truth, is easy to see. It means that it may be feasib... | python |
"""
Sazonov, S. Yu., Ostriker, J. P., & Sunyaev, R. A. 2004, MNRAS, 347, 144
"""
import numpy as np
# Parameters for the Sazonov & Ostriker AGN template
_Alpha = 0.24
_Beta = 1.60
_Gamma = 1.06
_E_1 = 83e3
_K = 0.0041
_E_0 = (_Beta - _Alpha) * _E_1
_A = np.exp(2e3 / _E_1) * 2e3**_Alpha
_B = ((_E_0**(_Beta - _Alpha)) ... | python |
import sympy as sp
import numpy as np
import pickle
class SymbolicRateMatrixArrhenius(sp.Matrix):
"""
Symbolic representation of Arrhenius process rate matrix.
"""
class Symbols:
@classmethod
def _barrier_element_symbol(cls, i, j):
if i == j:
return 0
... | python |
"""Author: Brandon Trabucco.
Very the installation of GloVe is function.
"""
import glove
config = glove.configuration.Configuration(
embedding=50,
filedir="./embeddings/",
length=127,
start_word="</StArT/>",
end_word="</StoP/>",
unk_word="</UnKnOwN/>")
vocab, embeddings = glove.load(confi... | python |
# -*- coding: utf-8 -*-
'''
程序思想:
有两个本地语音库,美音库Speech_US,英音库Speech_US
调用有道api,获取语音MP3,存入对应的语音库中
主要接口:
word_pronounce() 单词发音
multi_thread_download() 单词发音的批量多线程下载
'''
import urllib.request
from concurrent.futures import ThreadPoolExecutor
import os
from playsound import playsound
class pronounciation():
def __init... | python |
# **********************************************************************
# Copyright (C) 2020 Johns Hopkins University Applied Physics Laboratory
#
# All Rights Reserved.
# For any other permission, please contact the Legal Office at JHU/APL.
# **********************************************************************... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 23:33:28 2020
@author: abhi0
"""
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
tempTilda=''
for i in digits:
tempTilda=tempTilda+str(i)
temp=re.split('',tempTilda)
... | python |
from unyt import unyt_array, unyt_quantity
from astropy.units import Quantity
import logging
from more_itertools import always_iterable
import numpy as np
pyxsimLogger = logging.getLogger("pyxsim")
ufstring = "%(name)-3s : [%(levelname)-9s] %(asctime)s %(message)s"
cfstring = "%(name)-3s : [%(levelname)-18s] %(asctim... | python |
import PIL
from PIL import Image, ImageOps, ImageEnhance
import numpy as np
import sys
import os, cv2
import csv
import pandas as pd
myDir = "..\GujOCR\Output"
#Useful function
def createFileList(myDir, format='.png'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=Fa... | python |
from __future__ import unicode_literals
import frappe
import re
def execute():
for srl in frappe.get_all('Salary Slip',['name']):
if srl.get("name"):
substring = re.search("\/(.*?)\/",srl.get("name")).group(1)
emp = frappe.db.get_value('Employee',{'name':substring},'user_id')
... | python |
# coding: utf-8
r"""timeout decorators for Windows and Linux
Beware that the Windows and the Linux decorator versions
do not raise the same exception if the timeout is exceeded
"""
import platform
# import errno
# import os
import signal
import multiprocessing
import multiprocessing.pool
from functools import wrap... | python |
import argparse
import calendar
import dotenv
import json
import libraries.api
import libraries.handle_file
import libraries.record
import logging
import logging.config
import os
import pandas as pd
import requests
import time
from csv import writer
from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredErro... | python |
import json
from csv import DictReader
def parse_txt(fd, settings):
return fd.read().splitlines()
def parse_csv(fd, settings):
return [dict(x) for x in DictReader(fd)]
def parse_json(fd, settings):
return json.load(fd)
| python |
import torch
import torch.nn as nn
import pytorchvideo
AVAILABLE_3D_BACKBONES = [
"i3d_r50",
"c2d_r50",
"csn_r101",
"r2plus1d_r50",
"slow_r50",
"slowfast_r50",
"slowfast_r101",
"slowfast_16x8_r101_50_50",
"x3d_xs",
"x3d_s",
"x3d_m",
"x3d_l",
]
class CNN3D(nn.Module):
... | python |
# Copyright 2016 VMware, 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 required by a... | python |
def distance(x, y):
return (x-y).norm(2,-1)
def invprod(x, y):
return 1/(((x*y).sigmoid()).sum(-1)) | python |
import os
import cv2
import numpy as np
if __name__ == '__main__':
# 启动一个dicom server,用于接收来自X光机的dicom文件
from pydicom.uid import ImplicitVRLittleEndian
from pynetdicom import AE, debug_logger, evt
from pynetdicom.sop_class import XRayAngiographicImageStorage
from pynetdicom.sop_class import _VERIFICATION_CL... | python |
from app.data_models.relationship_store import Relationship, RelationshipStore
relationships = [
{
"list_item_id": "123456",
"to_list_item_id": "789101",
"relationship": "Husband or Wife",
},
{
"list_item_id": "123456",
"to_list_item_id": "ghijkl",
"relations... | python |
import os
import gc
import gym
import random
import numpy as np
from collections import deque
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, epochs, state_dim, action_size=2, action_limit=1.):
super(Actor, self)._... | python |
#All MPOS
MPOS = {"Abilene": {"Jones": "253", "Taylor": "441"},
"Amarillo": {"Potter": "375", "Randall": "381"},
"Brownsville": {"Cameron": "061"},
"Bryan-College Station": {"Brazos": "041"},
"Capital Area": {"Bastrop": "021", "Burnet": "053", "Caldwell": "055", "Hays": "209", "Travis":... | python |
from drivers import *
print "Driver loaded"
from drivers.nidaq.asserv import Asserv
from PyDAQmx import *
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import sys
default_fm_dev = 400 # Profondeur de modulation (Hz pour 5 V)
fs = E8254A(gpibAdress=19,name="freqSyn... | python |
#!/usr/bin/env python3
#
# Copyright 2018 Brian T. Park <brian@xparks.net>
#
# MIT License
#
"""Monitor the output of the given serial port and echo the output to the
STDOUT. If nothing is seen on the serial output for more than 10 seconds, an
error message is printed.
If the --test flag is given, the output is assume... | python |
# Lint as: python3
# Copyright 2018, The TensorFlow Federated 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 ... | python |
import pandas as pd
pd.options.display.max_columns = None
from sklearn.preprocessing import OrdinalEncoder
from torchvision import datasets, transforms
import torch
import plotly.express as px
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append... | python |
import asyncio
import logging
from ottoengine import const, helpers
from ottoengine.model import dataobjects
_LOG = logging.getLogger(__name__)
# _LOG.setLevel(logging.DEBUG)
class RuleActionItem(object):
""" This is a single action step in an action sequence """
def get_dict_config(self) -> dict:
... | python |
import tests2 as t
t.testing(method = 'KIR', initial = 'sin', velocity = 'const')
t.testing(method = 'KIR', initial = 'sin', velocity = 'x')
t.testing(method = 'KIR', initial = 'sin', velocity = 'func')
t.testing(method = 'KIR', initial = 'peak', velocity = 'const')
t.testing(method = 'KIR', initial = 'peak', ve... | python |
import numpy as np
import tqdm
def add_iteration_column_np(df):
"""
Only used for numerical integral timings, but perhaps also useful for other timings with some
adaptations. Adds iteration information, which can be deduced from the order, ppid, num_cpu
and name (because u0_int is only done once, we h... | python |
"""
0.92%
"""
import collections
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = collections.deque()
self.minlist = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
... | python |
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It"s nice, because now 1) we have a top level
# README file and 2) it"s easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.... | python |
index = {'Halifax': 'Q2141',
'Los Angeles': 'Q65',
'Wilkesboro': 'Q1025995',
'New York': 'Q1384',
'Uvalde': 'Q868860',
'Saint James': 'Q7401398',
'Ottawa': 'Q1930',
'Newton': 'Q49196',
'Mahé':'Q277480',
'Milwaukee': 'Q37836',
'Pom... | python |
num=input("enter any number")
if num > 0:
print("positive")
elif num < 0:
print("negative")
else:
print("it is a zero")
| python |
import pyviz3d.visualizer as viz
import numpy as np
import math
def main():
v = viz.Visualizer()
v.add_arrow('Arrow_1', start=np.array([0, 0.2, 0]), end=np.array([1, 0.2, 0]))
v.add_arrow('Arrow_2', start=np.array([0, 0.5, 0.5]), end=np.array([0.5, 0, 0.5]), color=np.array([0, 0, 255]))
v.add_arrow('A... | python |
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.metrics import confusion_matri... | python |
# encoding=utf8
import jenkins_job_wrecker.modules.base
from jenkins_job_wrecker.helpers import get_bool, gen_raw
from jenkins_job_wrecker.modules.triggers import Triggers
PARAMETER_MAPPER = {
'stringparameterdefinition': 'string',
'booleanparameterdefinition': 'bool',
'choiceparameterdefinition': 'choice'... | python |
import itertools
import pymel.core as pm
import flottitools.test as mayatest
import flottitools.utils.materialutils as matutils
import flottitools.utils.skeletonutils as skelutils
import flottitools.utils.skinutils as skinutils
class TestGetSkinCluster(mayatest.MayaTestCase):
def test_get_skin_cluster_from_cube... | python |
import array
import unittest
import pickle
import struct
import sys
from pyhmmer.easel import Vector, VectorF, VectorU8
class _TestVectorBase(object):
Vector = NotImplemented
def test_pickle(self):
v1 = self.Vector(range(6))
v2 = pickle.loads(pickle.dumps(v1))
self.assertSequenceEqu... | python |
from distutils.core import setup
import requests.certs
import py2exe
setup(
name='hogge',
version='1.0.1',
url='https://github.com/igortg/ir_clubchamps',
license='LGPL v3.0',
author='Igor T. Ghisi',
description='',
console=[{
"dest_base": "ir_clubchamps",
"script": "main.py... | python |
import re
from abc import ABC
class TemplateFillerI(ABC):
def fill(self, template: str, entity: str, **kwargs):
return template.replace("XXX", entity)
class ItalianTemplateFiller(TemplateFillerI):
def __init__(self):
self._reduction_rules = {'diil': 'del', 'dilo': 'dello', 'dila': 'della', '... | python |
import gc
import os
import cv2
import numpy as np
import torch
from SRL4RL import SRL4RL_path
from SRL4RL.rl.utils.runner import StateRunner
from SRL4RL.utils.nn_torch import numpy2pytorch, pytorch2numpy, save_model
from SRL4RL.utils.utils import createFolder, loadPickle
from SRL4RL.utils.utilsEnv import (
NCWH2W... | python |
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
import pytz
import requests
from datetime import timedelta
import datetime
import math
import wargaming
from django.db.models.signals import pre_save
from django.db.models import Q
from django.contrib.postgres.fields import JSONField... | python |
"""
python setup.py sdist
twine upload dist/*
"""
import cv2
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
print("检测到cuda环境") | python |
import librosa as lr
import numpy as np
def mu_law_encoding(data, mu):
mu_x = np.sign(data) * np.log(1 + mu * np.abs(data)) / np.log(mu + 1)
return mu_x
def mu_law_expansion(data, mu):
s = np.sign(data) * (np.exp(np.abs(data) * np.log(mu + 1)) - 1) / mu
return s
def quantize_data(data, classes)... | python |
from random import randint
cpu = randint(0,5)
usuario = int(input('Digite um numero entre 0 a 5: '))
if(cpu == usuario):
print('\033[33;mAcertô, mizeravi!')
else:
print('Errou Zé Ruela') | python |
from DBMS_Software.queryProcessor.ReadGlobalDataDictionary import readGlobalDataDictionary
from DBMS_Software.queryProcessor.ReadGlobalDataDictionary import fetchFileFromGCP
import os
def createSQLDump():
print("Enter the TableName:")
TableName = input()
tableLocation = readGlobalDataDictionary(TableName)
... | python |
"""STACK Configs."""
import os
import yaml
config = yaml.load(open('stack/config.yml', 'r'), Loader=yaml.FullLoader)
PROJECT_NAME = config['PROJECT_NAME']
STAGE = config.get('STAGE') or 'dev'
# primary bucket
BUCKET = config['BUCKET']
# Additional environement variable to set in the task/lambda
TASK_ENV: dict = di... | python |
"""
Script for testing purposes.
"""
import zmq
def run(port=5555):
context = zmq.Context()
# using zmq.ROUTER
socket = context.socket(zmq.ROUTER)
# bind socket
socket.bind('tcp://*:{}'.format(port))
while True:
msg = socket.recv_multipart()
print('Received message {}'.format... | python |
from itertools import product
from string import ascii_lowercase
import numpy as np
import pytest
from pandas import (
DataFrame,
Index,
MultiIndex,
Period,
Series,
Timedelta,
Timestamp,
date_range,
)
import pandas._testing as tm
class TestCounting:
def test_cumcount(self):
... | python |
# Copyright 2019 The Bazel 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 applicable la... | python |
"""
Referral answer related API endpoints.
"""
from django.db.models import Q
from django.http import Http404
from django_fsm import TransitionNotAllowed
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_fra... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BookInfo',
fields=[
('id', models.AutoField(aut... | python |
from tests.system.common import CondoorTestCase, StopTelnetSrv, StartTelnetSrv
from tests.dmock.dmock import SunHandler
from tests.utils import remove_cache_file
import condoor
class TestSunConnection(CondoorTestCase):
@StartTelnetSrv(SunHandler, 10023)
def setUp(self):
CondoorTestCase.setUp(self)
... | python |
#!/usr/bin/env python3
# encoding=utf-8
#codeby 道长且阻
#email @ydhcui/QQ664284092
from core.plugin import BaseHostPlugin
import re
import socket
import binascii
import hashlib
import struct
import re
import time
class MongodbNoAuth(BaseHostPlugin):
bugname = "Mongodb 未授权访问"
bugrank = "高危"
def fi... | python |
"""
Example of how to make a MuJoCo environment using the Gym library.
"""
from pathlib import Path
from gym.envs.mujoco.mujoco_env import MujocoEnv
from gym.utils import EzPickle
class SpiderEnv(MujocoEnv, EzPickle):
"""
Spider environment for RL. The task is for the spider to move to the target button.
... | python |
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh... | python |
from mock.mock import patch
import os
import pytest
import ca_test_common
import ceph_volume_simple_activate
fake_cluster = 'ceph'
fake_container_binary = 'podman'
fake_container_image = 'quay.ceph.io/ceph/daemon:latest'
fake_id = '42'
fake_uuid = '0c4a7eca-0c2a-4c12-beff-08a80f064c52'
fake_path = '/etc/ceph/osd/{}-{}... | python |
import glob
import matplotlib.pyplot as plt
import pickle
import numpy as np
import os
import sys
from argparse import ArgumentParser
from utils import get_params_dict
def parseArgs():
"""Parse command line arguments
Returns
-------
a : argparse.ArgumentParser
"""
parser = Argument... | python |
from django.shortcuts import render_to_response, render
from django.contrib.auth.decorators import login_required
from grid_core.managers import GridManager
@login_required
def account_deshbord(request):
allfriends = GridManager.get_friends_user(request.user)
allgroups = GridManager.get_group_user(request.use... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pydbgen/pbclass/data_define.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
# P... | python |
import datetime as dt
from datetime import datetime
from datetime import timedelta
from .error import WinnowError
valid_rel_date_values = (
"last_full_week",
"last_two_full_weeks",
"last_7_days",
"last_14_days",
"last_30_days",
"last_45_days",
"last_60_days",
"next_7_days",
"next_1... | python |
"""
创建函数,在终端中打印矩形.
number = int(input("请输入整数:")) # 5
for row in range(number):
if row == 0 or row == number - 1:
print("*" * number)
else:
print("*%s*" % (" " * (number - 2)))
"""
def print_rectangle(number):
for row in range(number):
if row == 0 or row == number - 1:
prin... | python |
import os.path
# manage descriptive name here...
def input_file_to_output_name(filename):
get_base_file = os.path.basename(filename)
base_filename = get_base_file.split('.')[0]
# base_filename = '/pipeline_data/' + base_filename
return base_filename | python |
# Import Modules
from module.Mask_RCNN.mrcnn import config as maskconfig
from module.Mask_RCNN.mrcnn import model as maskmodel
from module.Mask_RCNN.mrcnn import visualize
import tensorflow as tf
import numpy as np
import warnings
import json
import cv2
import os
# Ignore warnings
old_v = tf.compat.v1.logging.get_verb... | python |
from django.urls import path
from api import views
app_name = "api"
urlpatterns = [path("signup/", views.SignUp.as_view(), name="signup")]
| python |
import os
from glob import glob
from os.path import join, basename
import numpy as np
from utils.data_utils import default_loader
from . import CDDataset
class OSCDDataset(CDDataset):
__BAND_NAMES = (
'B01', 'B02', 'B03', 'B04', 'B05', 'B06',
'B07', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12'
... | python |
"""All the url endpoint hooks for facebook"""
import os
from sanic.response import json, text
from sanic import Blueprint
from .base import FacebookResponse
from taggo.parsers import FacebookYamlExecutor
VERIFY_TOKEN = os.environ.get("VF_TOKEN")
fb = Blueprint('facebook', url_prefix="/fb")
@fb.post('/recieve_message... | python |
from flask import render_template, url_for, request, redirect, session, flash
from home_password.models.user import User
from home_password.models.site import Site
from flask_login import login_user, current_user, logout_user
from flask import Blueprint
main = Blueprint('main', __name__)
@main.route('/')
@main.rout... | python |
"""*Text handling functions*."""
import json
import subprocess
import sys
from os.path import basename, splitext
from pathlib import Path
from urllib.parse import urlparse
from loguru import logger as log
import iscc_sdk as idk
__all__ = [
"text_meta_extract",
"text_extract",
"text_name_from_uri",
]
TEX... | python |
import data_processor
import model_lib
if __name__ == "__main__":
train_set = data_processor.read_dataset("preprocessed/training_nopestudio.json")
valid_set = data_processor.read_dataset("preprocessed/validation_nopestudio.json")
combined_set = data_processor.read_dataset("preprocessed/dataset_nopestudio.... | python |
import numba as nb
import numpy as np
class Zobrist(object):
MAX_RAND = pow(10, 16)
BLACK_TABLE = np.random.seed(3) or np.random.randint(MAX_RAND, size=(8, 8))
WHITE_TABLE = np.random.seed(7) or np.random.randint(MAX_RAND, size=(8, 8))
@staticmethod
def from_state(state):
return Zobrist.h... | python |
#!/usr/bin/env python
"""
CloudFormation Custom::FindImage resource handler.
"""
# pylint: disable=C0103
from datetime import datetime
from logging import DEBUG, getLogger
import re
from typing import Any, Dict, List, Tuple
import boto3
from iso8601 import parse_date
log = getLogger("cfntoolkit.ec2")
log.setLevel(DEBU... | python |
import rsa
from django.db import models
import base64
class RSAFieldMixin(object):
def loadKeys(self, keys=[]):
if len(keys) == 0:
(pubkey, privkey) = rsa.newkeys(512)
keys.append(pubkey)
keys.append(privkey)
elif len(keys) == 2:
pubkey = keys[0]
... | python |
import tensorflow as tf # for deep learning
import pathlib # for loading path libs
# data loader class
class DataLoader():
# init method
def __init__(self, path_to_dir):
self.__path_to_dir = pathlib.Path(path_to_dir)
# proecess image method
# @tf.function
def process_image(self, image_data... | python |
import json
from wtforms import widgets
class CheckboxInput(widgets.CheckboxInput):
def __call__(self, field, **kwargs):
kwargs.update({"class_": "checkbox-field"})
rendered_field = super().__call__(field, **kwargs)
return widgets.HTMLString(
"""
%s<label class="st... | python |
import heterocl as hcl
import numpy as np
def test_zero_allocate():
def kernel(A):
with hcl.for_(0, 10) as i:
with hcl.for_(i, 10) as j:
A[j] += i
return hcl.compute((0,), lambda x: A[x], "B")
A = hcl.placeholder((10,))
s = hcl.create_schedule(A, kernel)
p ... | python |
import abc
class LayerBase(object):
"""Base class for most layers; each layer contains information which is
added on top of the regulation, such as definitions, internal citations,
keyterms, etc."""
__metaclass__ = abc.ABCMeta
# @see layer_type
INLINE = 'inline'
PARAGRAPH = 'paragraph'
... | python |
import os
import hashlib
from download.url_image_downloader import UrlImageDownloader
def test_download_image_from_url():
url = ('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/RacingFlagsJune2007.jpg/575px-'
'RacingFlagsJune2007.jpg')
image_path = 'test.jpg'
# download the image
... | python |
#!/router/bin/python
from trex_general_test import CTRexGeneral_Test
from tests_exceptions import *
from interfaces_e import IFType
from nose.tools import nottest
from misc_methods import print_r
class CTRexNbar_Test(CTRexGeneral_Test):
"""This class defines the NBAR testcase of the T-Rex traffic generator"""
... | python |
from rest_framework import permissions
from rest_framework.reverse import reverse
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to... | python |
from ms_deisotope.peak_dependency_network.intervals import Interval, IntervalTreeNode
from glycan_profiling.task import TaskBase
from .chromatogram import Chromatogram
class ChromatogramForest(TaskBase):
"""An an algorithm for aggregating chromatograms from peaks of close mass
weighted by intensity.
Th... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('documents', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='InformationDocument',
fi... | python |
import re
class Command:
def __init__(self, name, register, jump_addr=None):
self.name = name
self.register = register
self.jump_addr = jump_addr
class Program:
def __init__(self, commands, registers):
self.commands = commands
self.registers = registers
self.i... | python |
if __name__ == "__main__":
import argparse
import os
import torch
import torch.nn as nn
import torch.optim as optim
from mnistconvnet import MNISTConvNet
from mnist_data_loader import mnist_data_loader
from sgdol import SGDOL
# Parse input arguments.
parser = ar... | python |
# -*- coding: utf-8 -*-
# @Time : 2019/9/8 14:18
# @Author : zhoujun
import os
import cv2
import torch
import subprocess
import numpy as np
import pyclipper
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
def de_shrink(poly, r=1.5):
d_i = cv2.contourArea(poly) * r / cv2.arcLength(poly, True)
pco =... | python |
count = 0
print('Before', count)
for thing in [9, 41, 12, 3, 74, 15]:
count += 1
# zork = zork + 1
print(count, thing)
print('After', count)
| python |
# import src.stacking.argus_models
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.