content stringlengths 5 1.05M |
|---|
import os
def get_project_dir():
return os.path.dirname(os.path.abspath(__file__))
def get_output_dir():
out = os.path.join(get_project_dir(), 'out')
os.makedirs(out, exist_ok=True)
return out
def get_data_dir():
return os.path.join(get_project_dir(), 'data')
|
import unittest
from cassyy import (
CASClient,
CASError,
CASInvalidServiceError,
CASInvalidTicketError,
)
class CASClientTestCase(unittest.TestCase):
cas_login_url = 'https://cas.local/login'
cas_logout_url = 'https://cas.local/logout'
cas_validate_url = 'https://cas.local/p3/serviceVali... |
# Lendo um valor em real, a cotação em dolar e imprimindo o valor em dolar
real = float(input('Entre com valor em real(R$): '))
cotacao = float(input('Entre com a cotação do dolar($): '))
conversao = real * cotacao
print(f'O valor R${real} com a cotação atual de R${cotacao}, corresponde ao valor de U${conversao:.2f}'... |
"""
@Author: hezf
@Time: 2021/6/3 14:42
@desc:
"""
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
import torch
import torch.optim as optim
from utils import *
from copy import deepcopy
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from itertools impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c) 2019, Gianluca Fiore
#
# 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
# th... |
import os
import logging
import sys
import numpy as np
import fitsio
import joblib
import tqdm
from ngmix.metacal import get_all_metacal
from ngmix.prepsfmom import PGaussMom
from wldeblend_sim import init_wldeblend, get_gal_wldeblend, make_ngmix_obs
from ngmix_maxlike import run_maxlike
LOGGER = logging.getLogger(__... |
from setuptools import setup
setup(name='gscrapper',
version='0.1',
description='Let you scrape images from google photo',
url='http://github.com/storborg/funniest',
author='Flying Circus',
author_email='flyingcircus@example.com',
license='MIT',
packages=['funniest'],
zi... |
#!/usr/bin/env python3
"""
Open source data downloader
Created: 10/15/2020 Max Bertolero (mb3152@seas.upenn.edu)
"""
__doc__ = """
This python library takes in a list of subjects, the data source,
and the data type you want, and downloads them. It then can delete them.
"""
import pkg_resources as pkgrf
import argpar... |
import os
import tensorflow as tf
from modules.models import RRDB_Model, DiscriminatorVGG128, mrUNet
from modules.lr_scheduler import MultiStepLR
from modules.losses import (PixelLoss, ContentLoss, DiscriminatorLoss,
GeneratorLoss)
from modules.utils import (load_yaml, load_dataset, Progres... |
from typing import Dict, List, Any
import numpy
from overrides import overrides
from ..instance import TextInstance, IndexedInstance
from ...data_indexer import DataIndexer
class TaggingInstance(TextInstance):
"""
A ``TaggingInstance`` represents a passage of text and a tag sequence over that text.
The... |
import numpy as np
def gini(array):
"""Calculate the Gini coefficient of a numpy array."""
# based on bottom eq:
# http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
# from:
# http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
# All values are trea... |
import pygame
import consoleHandling
import tilemap
from player import Player
class Game:
def __init__(self):
"""
State 0: Menu
State 1: Game
State 2: Pause
"""
self.state = 1
# Load spritesheet
consoleHandling.printToGameConsole("Loading... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" timeseriesframeinterface.py
Description:
"""
# Package Header #
from ..__header__ import *
# Header #
__author__ = __author__
__credits__ = __credits__
__maintainer__ = __maintainer__
__email__ = __email__
# Imports #
# Standard Libraries #
from abc import abstractme... |
from dataclasses import asdict
from sanic.response import json
from extra_hours.account.commands import CreateUserCommand, AuthenticateUserCommand, ChangeUserPasswordCommand
def init_account(**kwargs):
app = kwargs.get('app')
uow = kwargs.get('uow')
get_create_user = kwargs.get('get_create_user')
ge... |
import asyncio
from datetime import datetime
from io import BytesIO
from typing import Tuple
import PIL
from aiohttp import ClientSession
from ..errors import (InvalidContentType, InvalidToken, JsonDecodeException,
RequestError)
from ..ratelimit import RateLimiter
from ..request import Request
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# QTPyLib: Quantitative Trading Python Library
# https://github.com/ranaroussi/qtpylib
#
# Copyright 2016-2018 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... |
# $Id$
#
# Copyright (C) 2001-2008 greg Landrum
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
"""utility functions for clustering
"""
def Ge... |
from django.db import models
from djcelery.models import TaskMeta
from jsonfield import JSONField
from asset.models import AssetInfo
__all__ = [
'Tools',
'ToolsResults',
'Variable'
]
cmd_list = [
'shell',
]
class Tools(models.Model):
TOOL_RUN_TYPE = (
('shell', 'shell'),
('python'... |
import pandas
import numpy
import sys
import unittest
import os
import copy
import warnings
import tempfile
from isatools import isatab
sys.path.append("..")
import nPYc
from nPYc.enumerations import AssayRole, SampleType
from nPYc.utilities._nmr import qcCheckBaseline
from generateTestDataset import generateTestDatas... |
from django.contrib import admin
from bug.models import Bug
class BugAdmin(admin.ModelAdmin):
list_display = ['bugname ', 'bugdetail ', ' bugstatus', ' buglevel', ' bugcreater', ' bugassign', 'create_time','id']
admin.site.register(Bug) # 把Bug管理模块注册到Django admin后台并能显示
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Em on 2018/1/9
import time
import jieba
import sys
import tb_login
import threading
from api import *
from tb_api import *
from tb_api import get_api_urls
import sys
import getopt
# def main():
# crawler_threads = []
# cookie = tb_login.get_cookies(... |
"""prawdditions setup.py."""
import re
from codecs import open
from os import path
from setuptools import find_packages, setup
PACKAGE_NAME = "prawdditions"
HERE = path.abspath(path.dirname(__file__))
with open(path.join(HERE, "README.rst"), encoding="utf-8") as fp:
README = fp.read()
with open(path.join(HERE, P... |
# noinspection PyUnresolvedReferences
from api.imagestore.base.views import * # noqa: F401,F403
# noinspection PyUnresolvedReferences
from api.imagestore.image.views import * # noqa: F401,F403
|
import json
import sys
import time
import logging
from json.decoder import JSONDecodeError
from kafka_postgres.definitions.keys import MessageJsonKeys
from kafka_postgres.kafka_helper.consumer import Consumer
from kafka_postgres.kafka_helper.producer import Producer
from kafka_postgres.postgresql_helper.exceptions imp... |
# -*- coding: utf-8 -*-
"""
Autor: André Pacheco
Email: pacheco.comp@gmail.com
Function to load the CNN models
"""
from effnet import MyEffnet
from densenet import MyDensenet
from mobilenet import MyMobilenet
from resnet import MyResnet
from vggnet import MyVGGNet
from inceptionv4 import MyInceptionV4
from senet impo... |
import random
from django.urls import reverse
from faker import Faker
from rest_framework import status
from openbook_common.tests.models import OpenbookAPITestCase
import logging
import json
from openbook_common.tests.helpers import make_user, make_authentication_headers_for_user, \
make_community
logger = log... |
import random
from .behaviour import Behaviour
REGROUP_RANGE = 32
RETREAT_AMT = 16
class Base(Behaviour):
def complete_init(self):
# these are pointers. be careful with modifying them.
self.target_unit = None
self.reference_entity = None
self.valid_targets = []
self.sprea... |
from gym.envs.registration import register
#id='BitFlipper-n:space_seed'
register(
'BitFlipper2-v0',
entry_point='gym_BitFlipper.envs:BitFlipperEnv',
max_episode_steps=2,
kwargs = {"space_seed":0,"n":2}
)
register(
'BitFlipper5-v0',
entry_point='gym_BitFlipper.envs:BitFlipperEnv',
max_episo... |
#!/usr/bin/env python3
"""
Exctractor class enables retrieving all nlp features from `sentence`.
Designed for python3 which requires the pattern package to be installed
using the development brach https://github.com/clips/pattern#installation
"""
__author__ = "Ivo Merchiers"
__copyright__ = "Copyright 2017, Kn... |
# coding=utf8
import asyncio
import json
import logging
import sys
from datetime import datetime
from pathlib import Path
from shutil import rmtree, which
from tempfile import gettempdir
from typing import Any, List, Optional, Union
import click
from black_primer import __version__, lib
# If our environment has uvl... |
"""
You can remove this test after writing your own tests.
"""
def test_dummy():
assert True
|
import os
from setuptools import find_packages, setup
import versioneer
readMeFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md")
if os.path.exists(readMeFile):
with open(readMeFile, encoding="utf-8") as readMeFile:
long_description = readMeFile.read()
else:
long_description... |
# Generated by Django 3.2.8 on 2021-11-26 01:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0002_recipe_fat'),
]
operations = [
migrations.AddField(
model_name='category',
name='image',
fi... |
from datetime import datetime
from mycroft import MycroftSkill, intent_handler
import os
from yeelight import *
class Yeelight(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
def initialize(self):
self.bulb = Bulb("192.168.1.60")
self.log.info("Yeelight Bulb initilized"... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head:
return None
f = head
... |
from flask_restful import Resource, reqparse
from flask import jsonify
class Add(Resource):
def get(self):
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('operand1', type=int, required=True, help='operand1 is required The detail error is{error_msg}')
parser.add_argument('operand2... |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2020 Henny Si... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Attention(nn.Module):
def __init__(self, embedding_dim = 64, num_heads=1, softmax_temperature=1.0):
super().__init__()
self.fc_createheads = nn.Linear(embedding_dim, num_heads * embedding_dim)
self.... |
""" Created by Max 10/4/2017 """
from __future__ import division
import random
import math
from typing import Dict, Tuple, List
class CrossValidation:
def __init__(self, folds, learner):
"""
Constructor
:param folds: num folds
:param learner: the k-NN algorithm to use.
""... |
from Jarvis import JarvisAssistant
import re
import os
import random
import pprint
import datetime
import requests
import sys
import urllib.parse
import pyjokes
import time
import pyautogui
import pywhatkit
import wolframalpha
from PIL import Image
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import Q... |
import celery
from analysis.models import VariantTag, Analysis
from analysis.models.nodes.node_utils import update_analysis
from library.guardian_utils import admin_bot
from snpdb.clingen_allele import populate_clingen_alleles_for_variants
from snpdb.liftover import create_liftover_pipelines
from snpdb.models import I... |
# import modules urllib, thread, lock and queue
import urllib.request, urllib.error
from threading import Thread, Lock
from queue import Queue
q = Queue()
list_lock = Lock()
discovered_usernames = []
# scan_sites from username
def scan_sites(username):
global q
while True:
sites = q.get... |
import sys
def parse(filename="/usr/include/linux/input.h"):
f = open(filename)
ord_desc_map = {}
for l in f:
l = l.strip()
s = l.split()
if len(s) < 3:
continue
if s[0] != "#define" or not s[1].startswith("KEY_"):
continue
key_val = s[2]
... |
UNITS = {
'cd': 1.0,
'cp': 0.981,
'hk': 0.920,
} |
import unittest
from algorithms.say_number import say
class SayTest(unittest.TestCase):
def setUp(self):
try:
self.assertRaisesRegex
except AttributeError:
self.assertRaisesRegex = self.assertRaisesRegexp
def assertRaisesWithMessage(self, exception):
return se... |
import argparse
import os
import time
import uuid
from backbone.base import Base as BackboneBase
from config.eval_config import EvalConfig as Config
from dataset.base import Base as DatasetBase
from evaluator import Evaluator
from logger import Logger as Log
from model import Model
from roi.pooler import Pooler
def... |
import datetime
from cache_memoize import cache_memoize
from biblepaycentral.biblepay.clients import BiblePayRpcClient
@cache_memoize(timeout=3600)
def estimate_blockhittime(height):
""" we try to calculate when the block will hit.
For that, we get the current block, 500 blocks int he past, take the... |
# Generated by Django 2.1.5 on 2019-02-06 17:06
from django.db import migrations
class Migration(migrations.Migration):
atomic=False
dependencies = [
('bookshelf', '0015_auto_20190206_1703'),
]
operations = [
migrations.RenameModel(
old_name='A_Log',
new_name=... |
"""
In PyAnsys I type
```
test_result = pyansys.open_result('sample.rst')
estress,elem,enode = test_result.element_stress(0)
print(estress[23])
print(enode[23])
```
And get
```
[[nan nan nan nan nan nan]
[nan nan nan nan nan nan]
[nan nan nan nan nan nan]
[nan nan nan nan nan nan]]
[ 1 82 92 8]
```
And in Ansys I ... |
import uuid
from django.conf import settings
from django.db import models
from django.db.models.functions import Now
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from config.utils import upload_to_classname_uuid
class Safe(models.Model):
'''
Model representing use... |
"""Entry point of this module."""
import json
import logging
import logging.config
import os
import time
from pathlib import Path
from py_parser_sber.sberbank_parse import SberbankClientParser
from py_parser_sber.utils import (
Retry,
get_transaction_interval,
)
logger = logging.getLogger(__name__)
def _se... |
from graphsage.utils import load_data
from graphsage.supervised_train import train
import sys
def main(targets):
train_data = load_data('data/sage_NBA/nba')
train(train_data)
if __name__ == '__main__':
targets = sys.argv[1:]
main(targets)
|
import os.path as op
camcan_path = '/storage/store/data/camcan'
camcan_meg_path = op.join(
camcan_path, 'camcan47/cc700/meg/pipeline/release004/')
camcan_meg_raw_path = op.join(camcan_meg_path, 'data/aamod_meg_get_fif_00001')
mne_camcan_freesurfer_path = (
'/storage/store/data/camcan-mne/freesurfer')
deriva... |
import pyrr
import glfw
import numpy as np
from math import sin, cos
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
from lib.util.obj import ObjLoader
from lib.util.texture import load_texture
##############################################################################
# shader... |
#
#
# Copyright [2015] [Benjamin Marks and Riley Collins]
#
# 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
#
# U... |
"""Installation module."""
from setuptools import setup, find_packages
def main():
"""Code to be executed on install."""
setup(
name="qsimov-Mowstyl",
version="4.0.0",
author="Hernán Indíbil de la Cruz Calvo",
author_email="HernanIndibil.LaCruz@alu.uclm.es",
license="MI... |
"""
Gamma matrices
"""
__all__ = [
"numpy",
"outer",
"gamma_matrices",
"requires_numpy",
]
from .extensions import lazy_import, raiseif
try:
numpy = lazy_import("numpy")
_err = None
except ImportError as err:
numpy = None
_err = err
requires_numpy = raiseif(numpy is None, _err)
@re... |
from typing import List
# Replace pass with your solution
def ways_up(n: int, step_sizes: List[int] = [1, 2]) -> int:
"""Return the number of ways to get up the stairs
Calculate the number of paths up the stairs, where:
- `n` is the size of the staircase, i.e. the number of stairs
- `step_siz... |
import candle
import iisignature
import torch
import torch.autograd as autograd
import torch.nn as nn
import warnings
def sig_dim(alphabet_size, depth):
"""Calculates the number of terms in a signature of depth :depth: over an alphabet of size :alphabet_size:."""
return int(alphabet_size * (1 - alphabet_size ... |
#!/usr/bin/env python3
# Copyright 2020 Efabless 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 applica... |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework_inclusions.renderer import InclusionJSONRenderer
from .models import (
Basic,
BasicM2M,
C,
Child,
ChildProps,
Container,
E,
Entry,
MainO... |
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import images
from google.appengine.api.labs import taskqueue
... |
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from django.views import generic
from .models import Settlement
class IndexView(generic.ListView):
template_name = 'settlement/index.html'
context_object_name = 'settlement_list'
def get_queryset(self):
re... |
# coding:utf-8
# 2019-1-25
# sklearn 常用回归函数
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge, RidgeCV, RANSACRegressor
from sklearn.linear_model import Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import ElasticNet, SGDRegressor, BayesianR... |
import argparse
import os
import shlex
import tempfile
import pytest
import west.cmd.project
MANIFEST_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'manifest.yml')
)
# Where the projects are cloned to
NET_TOOLS_PATH = 'net-tools'
KCONFIGLIB_PATH = 'sub/kconfiglib'
COMMAND_OBJECTS = (
wes... |
import logging
import unittest
from io import BytesIO
from datetime import datetime
from goodline_iptv.jtvfile import JtvFile
from goodline_iptv.xmltv import XmltvBuilder
from goodline_iptv.test.jtv_data import TV_ZIP
from teamcity import is_running_under_teamcity
from teamcity.unittestpy import TeamcityTestRunner
lo... |
import sys
import os
from tkinter import Button
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Célia Cachos')
self.setWindowIcon(QIcon('imagens/logo.png'))
... |
import click
import codecs
import csv
import numpy as np
import os.path
import glob
from music21 import corpus
from sklearn.decomposition import PCA
from collections import defaultdict, Counter
from datasets import build_vocabulary
from constants import *
@click.group()
def score():
"""Tools for scoring MusicXM... |
# An example cipher suite for secure on-board communication. This is
# in no way cryptographically secure. DO NOT USE IN THE REAL WORLD!
from cantools.database import Message
from typing import Union
class SnakeOilAuthenticator:
"""A snake oil authenticator for secure on-board communication
The sole purpose... |
import subprocess
import re
def download(build_url, local_path):
print("Build-URL: {}".format(build_url))
print("Local-PATH: {}".format(local_path))
if not build_url: return False
retval = ""
status = False
curl_cmd = "curl --retry 15 -o {} {}".format(local_path, build_url)
for count in ... |
"""Cleanup unhosted and rogue pipe and duct insulation."""
from __future__ import print_function
import collections
import datetime
import itertools
import clr
clr.AddReference("RevitAPI")
clr.AddReference("RevitAPIUI")
import Autodesk.Revit.DB as db
import Autodesk.Revit.UI as ui
clr.AddReference("System.Windows.Form... |
'''
Tipos de dados
str - string - textos 'Assim' ou "Assim"
int - inteiro - 12345 0 -9 10 -11
float - real/ponto flutuante 16.65 -10.6
bool - booleano/lógico - True/False
'''
print('- Isaac', type('Luiz'))
print('-', 10, type(10))
print('-', 23.25, type(23.25))
print('-', 10==10, type(10==10))
print... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
cl... |
from bs4 import BeautifulSoup as bs
import os
import threading
import requests
import random
host = "http://index-of.co.uk/"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}
"""
with requests.Session() as s:
page = s.g... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Secrets Manager"
prefix = "secretsmanager"
class Action(BaseAction):
def __init__(self, action: str = None) -> Non... |
from django.apps import AppConfig
class AzuremanagementConfig(AppConfig):
name = 'AzureManagement'
|
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class MusicWorks(db.Model):
__tablename__ = "music_works"
iswc = db.Column(db.String, unique=True, primary_key=True)
title = db.Column(db.String)
contributors = db.Column(db.String)
sources = db.Column(db.String) |
import yaml
import sys
def dereferenceAll(obj, parent):
if type(obj) is dict:
for fieldStr in obj:
#print(fieldStr)
if(fieldStr == '$ref'):
refPath = obj[fieldStr].split('/')
refObj = parent
for refPart in refPath:
... |
from enum import Enum
class ThresholdType(Enum):
AVG = "avg"
MAX_FRACT_2 = "maxdiv2"
|
# -*- coding:utf-8 -*-
# responses.py
import os, sys
import re
import mimetypes
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound, \
HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseForbidden, \
HttpResponseServerError, Http404, ... |
# MIT License
#
# Copyright (c) 2021 Clivern
#
# 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, modify, merge, publ... |
# coding=utf-8
import logging
import imaplib
import os
import re
from . import app_settings
from .models import (
IP,
LocationLocal
)
from celery.task import (
PeriodicTask,
Task,
)
from datetime import timedelta
from django.conf import settings
from shared.utils import list_remove_duplicates
lo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: util.py
#
# 通用函数库
#
import hashlib
def to_bytes(data):
if isinstance(data, bytes):
return data
elif isinstance(data, (str, int, float)):
return str(data).encode("utf-8")
else:
raise TypeError
MD5 = lambda data: hashlib.md... |
import aoc
# read polymer and templates
polymer, raw_templates = aoc.blocks("14_in.txt")
templates = dict(line.split(" -> ") for line in aoc.lines(raw_templates))
# do 10 iterations of inserting
for _ in range(10):
new_polymer = ""
for index in range(len(polymer)-1):
pair = polymer[index:index+2]
... |
import asyncio
import pathlib
from fastapi.testclient import TestClient
from mainpy import main
from jax_pep503.main import app, get_package_links
HTML_DIR = pathlib.Path('./docs')
client = TestClient(app)
def build_index():
asyncio.run(_build_index())
@main
async def _build_index(html_dir: pathlib.Path = ... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class form_cadastro_livro(FlaskForm):
titulo = StringField('Título')
isbn = StringField('ISBN')
autor = StringField('Autor')
anoPublicacao = StringField('Ano publicação')
estoque = StringField('Estoque')
preco = String... |
import sys
import signal
import cv2
from contextlib import contextmanager
class Color: # pylint: disable=W0232
GRAY = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
CRIMSON = 38
def colorize(num, string, bold=False, highlight=False):
assert is... |
#!/usr/bin/env python3
from transport.transport_tcp import TransportTCP
from transport.transport_serial import TransportSerial
from protocol.communicator import Communicator
from protocol.defs.defs2x6.defs2x6 import *
from protocol.wrapper import *
import time
import json
from json import JSONEncoder
def _default(self... |
from py42.exceptions import Py42BadRequestError
from py42.exceptions import Py42CloudAliasLimitExceededError
from py42.services import BaseService
class DetectionListUserService(BaseService):
"""Administrator utility to manage High Risk employees information.
`Support Documentation <https://support.code42.co... |
import os
from ingest.process.detection.src.preprocess import pad_image
from PIL import Image
import glob
import click
from ingest.process.proposals.connected_components import get_proposals
import shutil
from joblib import Parallel, delayed
import shutil
def process_f(f, pth):
basename = os.path.basename(f)[:-4]... |
# -*- coding: utf-8 -*-
# Copyright .
# Author:
#
# cython: language_level=3
#
import copy
import json
import six
import math
import torch
from lib.handler import load_bert, get_vocab_size
import lib.config as cf
from lib.utils import reshape_tensor, mask, find_max_proper_batch, gelu
from torch.nn import functional
fr... |
def square_of_the_sum(N):
return ((N * (N + 1)) / 2) ** 2
def sum_of_the_squares(N):
return (N * (N + 1) * (2 * N + 1)) / 6
def difference(N):
diff = square_of_the_sum(N) - sum_of_the_squares(N)
print("diff is: ",diff)
return diff
difference(100) |
# This is the code for experiments performed on the Eitz Sketches dataset for the DeLiGAN model. Minor adjustments
# in the code as suggested in the comments can be done to test GAN. Corresponding details about these experiments
# can be found in section 5.5 of the paper and the results showing the outputs can be see... |
import contextlib
import csv
import math
from datetime import datetime
from typing import Generator, Tuple
import numpy as np
from scipy import spatial
Point = Tuple[float, float]
def _load_data() -> Generator[Tuple[float, float], None, None]:
with open('coordinates.csv', 'r') as fp:
reader = csv.reader... |
from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
import ssl
from time import ctime
from kafka import KafkaProducer
# STEP to build socket server:
# 1 create handle class for handling the received request
# 2 create a server class (TCP,UDP...)
# 3 use server class to run the serve_forever() ... |
import boto3
import random
import string
# AWS clients
transcribe = boto3.client('transcribe')
def lambda_handler(event, context):
# Initialization
bucket = event['Records'][0]['s3']['bucket']['name']
file = event['Records'][0]['s3']['object']['key']
transcription_job = ''.join(
[random.choi... |
import argparse
import os
import torchvision.transforms as transforms
from src.datamanager import *
from src.datamanager import DataProvider
import src.datamanager.utils as datautils
from PIL import Image
from src.configs import *
from src.ml.net import PyNet
from src.results import performance
from src.results.reid im... |
#!/usr/bin/env python
# Copyright libOpenCOR contributors.
#
# 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 applicabl... |
import json
import sys
sys.path.append("..")
from util import Util
from model import ToolType
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = insta... |
from src.models.AbstractModel import AbstractModel
from keras.models import Sequential
from keras.layers import Dense, Lambda, Embedding
import keras.backend as K
from keras import optimizers
class Word2VecModel(AbstractModel):
def __init__(self, save_directory, vocabulary_size, output_dim, input_length):
super()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.