content stringlengths 5 1.05M |
|---|
import threading
import subprocess
import glob
import re
import operator
import pickle
from audio import spec2wav, wav2spec, read_wav, write_wav
import matplotlib.pyplot as plt
import numpy as np
sr = 22050
n_fft = 512
win_length = 400
hop_length = 80
duration = 2 # sec
# moving all data to one dir cd ~/Downloads/a... |
import unittest
from decimal import Decimal
from gsf.core.entity.core import Entity
from gsf.core.entity.properties import ExpressionProperty
from gsf.core.mathematics.values import Value
from gsf.dynamic_system.dynamic_systems import DiscreteEventDynamicSystem
from gsf.dynamic_system.future_event_list import Schedule... |
import numpy as np
import time
import scipy.io as sio
from ismore import brainamp_channel_lists
from riglib.brainamp.rda import *
fs = 1000
channels = brainamp_channel_lists.emg_eog2_eeg
total_time = 120 # how many secs of data to receive and save
n_samples = 2 * fs * total_time # allocate twice a... |
from Port import Port
import pytest
test_data = [('test1.txt',25,65),('test2.txt',5,127)]
test_data2 = [('test2.txt',5,62)]
@pytest.mark.parametrize("file_name,preamble_len,result",test_data)
def test_first_number_not_compliant(file_name,preamble_len,result):
port = Port(file_name,preamble_len)
assert port.fi... |
from django.urls import path
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from . import views
from .views import upload
urlpatterns = [
path('', upload, name='upload'),
path('home/', login_required(views.home), name='home_page'),
path('predict/', ... |
#!/usr/bin/python3
HOST = '0.0.0.0'
PORT = 10000
FLAG_PATH = '/flag'
SOURCE_PATH = '/demo.sol'
CONTRACT_NAME = 'Challenge'
EVENT_NAME = 'GetFlag'
INFURA_PROJECT_ID = ''
|
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2019. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use, line-too-long
"""Feed component implementation."""
import logging
import sys
import traceback
from pydoc import locate
from resilient_circuits import ResilientComponent, handler, ... |
#!/usr/bin/env python
# encoding: utf-8
# Copyright (c) 2021 Grant Hadlich
#
# 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... |
from datetime import tzinfo, timedelta, datetime
from django.core.management.base import BaseCommand, CommandError
from orders.models import subscription_product
from invoice.models import Invoice
#python manage.py checksubscription 2016-11-10
class Command(BaseCommand):
help = 'Check for expiry of subscriptions'
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
timecomplexity= O(n) spacecomplexity = O(n)
serialize
construct recusive function to covert tree into string replace None by '# ' and use ' ' to s... |
""" Module related to forgot password"""
from flask import Blueprint, flash, url_for, render_template
from itsdangerous import URLSafeTimedSerializer
from werkzeug.security import generate_password_hash
from werkzeug.utils import redirect
from auth.forms import ForgotForm, ResetForm
from auth.helpers import find_user_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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 ... |
#!/usr/bin/env python
import rospy
import std_msgs.msg
import phidgets.msg
import geometry_msgs.msg
#####################################################
# Initialize Variables #
#####################################################
ENCODER_LEFT = 0
ENCODER_RIGHT = 0
LINEAR_VELOCITY = 0.... |
import torch
from torch import nn
from conversion_config import Config
import torch.nn.functional as F
import math
class Attn(nn.Module):
def __init__(self,hidden_size):
super(Attn, self).__init__()
self.hidden_size = hidden_size
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
... |
# terrascript/resource/philips-software/hsdp.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:18:56 UTC)
import terrascript
class hsdp_ai_inference_compute_environment(terrascript.Resource):
pass
class hsdp_ai_inference_compute_target(terrascript.Resource):
pass
class hsdp_ai_inference_jo... |
#######################################################################
# This file is part of Pyblosxom.
#
# Copyright (c) 2002-2011 Will Kahn-Greene
#
# Pyblosxom is distributed under the MIT license. See the file
# LICENSE for distribution details.
###################################################################... |
import os
import time
import pickle
import numpy as np
import scipy.sparse as sp
import matplotlib.pyplot as plt
from keras import metrics
from keras import backend as K
from keras.models import Model
from keras.layers import (Input, Dense, Softmax, Lambda)
from keras.optimizers import Adagrad
from keras.initializers ... |
import numpy as np
import copy
from supervised.algorithms.registry import AlgorithmsRegistry
from supervised.algorithms.registry import BINARY_CLASSIFICATION
class HillClimbing:
"""
Example params are in JSON format:
{
"booster": ["gbtree", "gblinear"],
"objective": ["binary:logistic"],
... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=38):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
de... |
# -*- coding: utf-8 -*-
# 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... |
from encomp.constants import CONSTANTS
from encomp.units import Quantity
from encomp.utypes import Density, Pressure
def test_CONSTANTS():
assert isinstance(CONSTANTS.default_density, Quantity[Density])
assert isinstance(CONSTANTS.normal_conditions_pressure, Quantity[Pressure])
|
from __future__ import annotations
from unittest import TestCase
from jsonclasses.exceptions import ValidationException
from tests.classes.simple_article import SimpleArticle
class TestStr(TestCase):
def test_str_is_str_after_assigned(self):
article = SimpleArticle(title='Lak Lak')
self.assertEqu... |
from .dice import Dice
|
import unittest
import pandas as pd
import pandas.testing as pdt
import biom
import numpy as np
import numpy.testing as npt
from qiime2 import Artifact
from microsetta_public_api.models._taxonomy import GroupTaxonomy, Taxonomy
from microsetta_public_api.exceptions import (DisjointError, UnknownID,
... |
from django.db.models.expressions import Func, Expression
from pragmatic.models.expressions import F, Value
class Round(Func):
function = 'ROUND'
arity = 2
# https://github.com/primal100/django_postgres_extensions
class SimpleFunc(Func):
def __init__(self, field, *values, **extra):
if not isins... |
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... |
from myhdl import block, instance
@block
def serdes_1_to_5(use_phase_detector, data_in_p, data_in_n, rx_io_clock,
rx_serdes_strobe, reset, g_clock, bit_slip, data_out,
diff_term='TRUE', bit_slip_enable='TRUE', sim_tap_delay = 49):
"""
The block converts the serial data in... |
import os
NRESULTS_ALLOWED_SCHEMAS = ['nr_nresults/nr-nresults-v1.0.0.json']
NRESULTS_PREFERRED_SCHEMA = 'nr_nresults/nr-nresults-v1.0.0.json'
DRAFT_NRESULT_PID_TYPE = 'dnrnrs'
DRAFT_NRESULT_RECORD = 'nr_nresults.record:DraftNResultRecord'
PUBLISHED_NRESULT_PID_TYPE = 'nrnrs'
PUBLISHED_NRESULT_RECORD = 'nr_nresults... |
# -*- coding: utf-8 -*-
# Copyright 2015 www.suishouguan.com
#
# Licensed under the Private License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE
#
# Unless ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-10-17 13:31
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20181015_08... |
from sklearn.metrics import f1_score
import torch
import torch.nn as nn
from torch.nn import Module
import torch.nn.functional as F
import math
import torch.optim as optim
import numpy as np
import time
from utils import inverse_norm
# from plot_fig.histogram import plot_histogram
def accuracy(output, labels):
p... |
from data_stack.io.resources import StreamedTextResource
import pandas as pd
import torch
from data_stack.dataset.iterator import DatasetIterator
class ArrhythmiaIterator(DatasetIterator):
def __init__(self, samples_stream: StreamedTextResource, targets_stream: StreamedTextResource):
self.samples = pd.re... |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Module testing the Legend SDLC Operator."""
import json
from charms.finos_legend_libs.v0 import legend_operator_testing
from ops import testing as ops_testing
import charm
class LegendSdlcTestWrapper(charm.LegendSDLCServerCharm):
@cl... |
# coding: utf-8
from __future__ import unicode_literals
from spacy.matcher import PhraseMatcher
from spacy.lang.en import English
from spacy.compat import pickle
def test_issue3248_1():
"""Test that the PhraseMatcher correctly reports its number of rules, not
total number of patterns."""
nlp = English()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/uwmadison-chm/masterfile
# Copyright (c) 2020 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Re... |
# Title: 우수 마을
# Link: https://www.acmicpc.net/problem/1949
import sys
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)
read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
def get_max(vil: int, select: int, ... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow
class Ui_createUserWidget(QMainWindow):
def __init__(self):
super(Ui_createUserWidget, self).__init__()
self.setupUi()
def setupUi(self):
self.setObjectName("createUserWidget")
self.setFixedSize(... |
#!/usr/bin/env python
from __future__ import print_function
__author__ = 'Whirliwig'
__license__ = 'MIT'
__version__ = '0.5'
__email__ = 'ant@dervishsoftware.com'
from os import path, chdir, listdir, walk, putenv
import shutil
import sys
import tomdoc_converter_objc
import subprocess
from tomdoc_converter_objc import... |
"""Tests for `otelib.strategies.dataresource`."""
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from typing import Callable, Union
from tests.conftest import OTEResponse, ResourceType
def test_create(
mock_ote_response: "OTEResponse",
ids: "Callable[[Union[ResourceType, str]], st... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Wed Jan 24 22:53:14 2018
# (c) Alexander Veledzimovich
"""
Setting for 0_spacewar.py
"""
__version__ = 0.1
class Setting():
"""
Constants
"""
def __init__(self):
self.FPS = 30
self.WID = 1024
self.HEI = 768
self.SCRWI... |
import difflib
import kaa
from kaa import document
from kaa.filetype.diff import diffmode
from kaa.filetype.default import keybind
from kaa.ui.dialog import dialogmode
class ViewDiffMode(dialogmode.DialogMode):
MODENAME = 'ViewDiff'
DOCUMENT_MODE = False
USE_UNDO = False
KEY_BINDS = [
keybind... |
"""
Name: SideStep
Version: 0.1.0
Date: 3/30/2015
Author: Josh Berry - josh.berry@codewatch.org
Github: https://github.com/codewatchorg/sidestep
Description: SideStep is yet another tool to bypass anti-virus software. The tool generates Metasploit payloads encrypted using... |
r"""
Laplace equation with Dirichlet boundary conditions given by a sine function
and constants.
Find :math:`t` such that:
.. math::
\int_{\Omega} c \nabla s \cdot \nabla t
= 0
\;, \quad \forall s \;.
The :class:`sfepy.discrete.fem.meshio.UserMeshIO` class is used to refine the
original two-element mesh ... |
# eastmoney stock crawler
# tools browser Developer Tools
import requests
def getHTMLText(url,headers):
try:
r = requests.get(url,headers=headers,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.json()
except:
return "123"
if __name__ == "__ma... |
# ----------------------------------------------------------------------
# RegexLabel model
# ----------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python modu... |
"""Tests for groove selection widget."""
import pytest
import weldx
from weldx.welding.groove.iso_9692_1 import _create_test_grooves
from weldx_widgets import WidgetGrooveSelection, WidgetGrooveSelectionTCPMovement
test_grooves = _create_test_grooves()
@pytest.mark.parametrize("groove_name", test_grooves.keys())
de... |
# coding=utf-8
"""Source registry.
This module provides a unique mixin _SourceFileRegistry to be
included in the Megamodel class.
"""
from collections import OrderedDict
from typing import List, Dict, Optional, ClassVar
from modelscript.base.exceptions import (
NotFound)
DEBUG = 0
Metamodel = 'Metamodel'
Metamo... |
from os import X_OK, pardir
print("""
**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To quit at any time, type "quit" **
**************************************
Appetizers
----------
Wings
Cookies
Spring Rolls
Entrees
-------
Salmon
Steak
M... |
import base64
import json
import os.path
from os.path import expanduser
from ditto.core import logger
def get(key):
cls = DittoConfig()
val = cls.get(key)
return val
def not_set(key):
cls = DittoConfig()
val = cls.get(key)
return val is None
def set(key, val):
cls = DittoConfig()
... |
#!/usr/bin/env python
# encoding: utf-8
"""
Handling of the generate subcommand
"""
# ---------------------------------------------------------------------------
# Standard imports:
import os
import subprocess
import shutil
# Local imports
from .. import codegen
from .. import modelutils
from .. import utils
from . im... |
from os.path import isfile, join, exists
import re
import click
import logging
from stable_world.output.helpers import indent
from stable_world.py_helpers import ConfigParser
from stable_world import errors
from stable_world.interact.yaml_insert import yaml_add_lines_to_machine_pre
from .base import BucketConfigurato... |
import numpy as np
import random
import json
import nltk
nltk.download('punkt')
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from nltk_utils import bag_of_words, tokenize, stem
from model import NeuralNet
with open('intents.json', 'r') as f:
intents = json.load(f)
all_word... |
import os
import sys
import bokeh.layouts as bkl
import bokeh.plotting as bkp
import numpy as np
# make it so we can import models/etc from parent folder
sys.path.insert(1, os.path.join(sys.path[0], '../common'))
from plotting import *
from bokeh.io import export_svgs
import cairosvg
size_x_axis = False
trial_num = ... |
from django.db.models.query_utils import Q
from care.facility.models.patient_consultation import PatientConsultation
from care.users.models import User
from care.utils.cache.cache_allowed_facilities import get_accessible_facilities
def get_consultation_queryset(user):
queryset = PatientConsultation.objects.all()... |
#Copyright 2018 OSIsoft, 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, softwar... |
# -*- coding: utf-8 -*-
import os
import urllib
import requests
import Foundation
from appscript import app, mactypes
import subprocess
class BingImageInfo:
def __init__(self):
self.jsonUrl = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US"
self.response = requests.get(self.jsonUrl).json()... |
#!/usr/bin/env python3
# Copyright 2017 University of Maryland.
#
# This file is part of Sesame. It is subject to the license terms in the file
# LICENSE.rst found in the top-level directory of this distribution.
from sesame.ui import mainwindow
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtGui
import s... |
#!/usr/bin/env python
from bourbaki.application.cli import CommandLineInterface, ArgSource
from typing import *
cli = CommandLineInterface(
prog="foo.py", arg_lookup_order=(ArgSource.CLI, ArgSource.DEFAULTS)
)
@cli.definition
class Foo:
"""command line interface called foo"""
def __init__(self, x: int =... |
import discord
from discord.ext import commands
from random import shuffle, randint
from asyncio import sleep
from utils.generalFuncs import return_weather, NewsFromBBC, indianNews
class generalCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.subChannel = []
@commands.command(name = 'start')
as... |
import argparse
import math
import subprocess
from datetime import datetime
import numpy as np
import tensorflow as tf
import socket
import importlib
import os,ast
import sys
from sklearn.cluster import KMeans
import h5py
np.set_printoptions(edgeitems=1000)
from scipy.optimize import linear_sum_assignment
BASE_DIR = o... |
import sys
def resolve(label):
"""
Given a result from htseq-count, resolve label
"""
if len(label) == 0:
return 'ID'
# one label -> return label
elif '__' not in label:
pieces = label.split(':')
return '{}:{}'.format(pieces[2], pieces[-1][:-1])
# no feature
el... |
#회원탈퇴
from discord.ext import commands
from discord.ext.commands import Context
from discord.ext.commands.errors import MissingRequiredArgument
from discord_slash import SlashContext, cog_ext
from discord_slash.model import SlashCommandOptionType as OptionType
from discord_slash.utils.manage_commands import create_op... |
from ..type import UIntType, SIntType
from . import Expression
from ..utils import serialize_str
class UIntLiteral(Expression):
def __init__(self, value, width):
self.value = value
self.tpe = UIntType(width)
def serialize(self, output):
self.tpe.serialize(output)
output.write(... |
#!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
#
# Author: Zhuo Chen <zhuoc@cs.cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... |
from header import *
from model import *
from config import *
from dataloader import *
from inference import Searcher
from es.es_utils import *
from .utils import *
def init_recall(args):
if args['model'] == 'bm25':
# Elasticsearch
searcher = ESSearcher(f'{args["dataset"]}_q-q', q_q=True)
... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v2.proto.resources import campaign_budget_pb2 as google_dot_ads_dot_googleads__v2_dot_proto_dot_resources_dot_campaign__budget__pb2
from google.ads.google_ads.v2.proto.services import campaign_budget_service_pb... |
nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
media = (nota1 + nota2) / 2
print(f'Tirando {nota1:.1f} e {nota2:.1f}, a média do aluno é {media:.1f}')
if media >= 7.0:
print('O aluno esta APROVADO!')
elif media >= 5.0 and media < 7:
print('O aluno está em RECUPERAÇÃO!')
elif medi... |
class Dog:
def __init__(self, name='chuchu',id=0):
self.name = name
self.id=id
def set_producer(self, producer):
self.producer = producer
|
import os
import sys
import base64
from django.db.models import F, Q
from xos.config import Config
from observer.syncstep import SyncStep
from core.models import Service
from hpc.models import ServiceProvider
from util.logger import Logger, logging
# hpclibrary will be in steps/..
parentdir = os.path.join(os.path.dirn... |
# Copyright (c) 2021.
#
# 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, so... |
# -*- coding: utf-8 -*-
import logging
from skimage.util.shape import view_as_windows
import numpy as np
import pandas as pd
__author__ = "Jannik Frauendorf"
__copyright__ = "Jannik Frauendorf"
__license__ = "mit"
_logger = logging.getLogger(__name__)
def create_sliding_windows(series, window_size):
"""
Com... |
from .constants import MAX_KEYNAME_LENGTH, MAX_VALUENAME_LENGTH
from .dtypes import create_unicode_buffer
from .dtypes import BYTE, LPVOID, DWORD, LONG, LPCWSTR, HKEY, LPWSTR, POINTER
from .dtypes import SECURITY_ATTRIBUTES, FILETIME
from .funcs import wrap_advapi32_function
class WrappedFunction(object):
_retur... |
import collections
import os, os.path
import subprocess
import logging
import sys
sym_dict = collections.OrderedDict({"Add":"+","Mul":"*","Pow":"^",
"StrictGreaterThan":">","GreaterThan":">=",
"StrictLessThan":"<","LessThan":"<=",
"And":"and", "Or":"or","Not":"not", "exp":"exp", "sin"... |
# Generated by Django 3.0.8 on 2020-08-19 11:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rest', '0033_auto_20200819_2058'),
]
operations = [
migrations.AlterField(
model_name='culture_event',
name='name',
... |
import errno
import logging
import os
import uuid
import struct
import time
import base64
import socket
from ceph_deploy.cliutil import priority
from ceph_deploy import conf, hosts, exc
from ceph_deploy.util import arg_validators, ssh, net
from ceph_deploy.misc import mon_hosts
from ceph_deploy.lib import remoto
from ... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import sys
import time
start_time = time.time()
use_keras = True
if use_keras:
use_cntk = False
if use_cntk:
try:
base_directory = os.path.split(sys.executable)[0]
os.environ['PATH'] += ';' + base_directory
import ... |
#!/usr/bin/env python
"""Client VFS handlers module root."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
|
from __future__ import absolute_import
from django.db.models import Q
from operator import or_
from rest_framework.response import Response
from six.moves import reduce
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.api.serializers import serialize
from sentry.api.serializers.models.group ... |
from .manager import Manager, ModelType, QuerySet, ListManager
from .related import one_to_many, one_to_one, get_manager
from .model import Model
from .schema import ListField |
from django.apps import AppConfig
class SharingcenterConfig(AppConfig):
name = 'sharingCenter'
|
# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
from os import listdir
from os import path
from glob import glob
def GetContours(image, thresh=150):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
grayBlur = cv.blur(gray, (3, 3))
canny = cv.Canny(grayBlur, thresh, thresh * 2)
contours = cv.f... |
#Python Arrays
#--------------------------------------------------------------------------------------------------------
#Python Classes and Objects
class MyClass:
x = 5
hola=MyClass()
print(hola.x)
##
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Pers... |
from __future__ import annotations
from typing import Callable, Union, Tuple
from fn import F
from ..util import dict_add
class Args(F):
"""
A variable wrapper for pipe operations.
Args:
args, kwargs: The arguments to be passed to the pipe.
Examples::
from tensorneko.util import ... |
a = 10
b = 20
c =30
d = 8
print("helloworld")
|
# Copyright (c) OpenMMLab. All rights reserved.
import os
import warnings
import numpy as np
from mmcv import Config
from xtcocotools.cocoeval import COCOeval
from ...builder import DATASETS
from .topdown_coco_dataset import TopDownCocoDataset
@DATASETS.register_module()
class TopDownCocoWholeBodyDataset(TopDownCoc... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Flask
from flask_assets import Environment, Bundle
import logging
from logging.handlers import RotatingFileHandler
from platus.web import web
from platus.api import api
from platus.config import config
application = Flask(__name__,\
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from torch.autograd import Variable
import torch
import os
import matplotlib.pyplot as plt
class TVLoss(torch.nn.Module):
def __init__(self,TVLoss_weight=1):
super(TVLoss,self).__init__(... |
def near_islands(game,my_pirate,islands):
nearest = 999999
dist = 0
closest_island=islands[0]
for island in islands:
dist = game.distance(my_pirate,island)
if island.team_capturing == game.NEUTRAL:
dist = dist / 2
if dist<nearest:
nearest = game.dista... |
"""
The main script that serves as the entry-point for all kinds of training experiments.
"""
import sys
from pathlib import Path
import pytorch_lightning as pl
from das.data.data_args import DataArguments
from das.data.data_modules.factory import DataModuleFactory
from das.model_analyzer.analyzer_args import Analysi... |
__file__ = 'OffSystem_v1'
__date__ = '5/29/14'
__author__ = 'ABREZNIC'
import os, arcpy, xlwt, datetime
#date
now = datetime.datetime.now()
curMonth = now.strftime("%m")
curDay = now.strftime("%d")
curYear = now.strftime("%Y")
today = curYear + "_" + curMonth + "_" + curDay
#variables
qcfolder = "C:\\TxDOT\\QC\\Off... |
from rest_framework import serializers
from thenewboston.constants.network import PRIMARY_VALIDATOR
from thenewboston.serializers.network_block import NetworkBlockSerializer
from thenewboston.transactions.validation import validate_transaction_exists
from v1.self_configurations.helpers.self_configuration import get_se... |
import sys
# Credit to Hugh Bothwell from http://stackoverflow.com/questions/5084743/how-to-print-pretty-string-output-in-python
class TablePrinter(object):
"Print a list of dicts as a table"
def __init__(self, fmt, sep=' ', ul=None):
"""
@param fmt: list of tuple(heading, key, width)
... |
import argparse
import sys
import datetime
import os
from mtsv.parameters import Parameters
from mtsv.commands import (
Init,
Readprep,
Binning,
Summary,
Analyze,
Extract,
Pipeline
)
from mtsv.parsing import (
TYPES,
make_sub_parser,
parse_config_sections,
get_missing_secti... |
"""
The 20 commonly occurring amino acids are abbreviated by using 20 letters from the English alphabet (all letters
except for B, J, O, U, X, and Z). Protein strings are constructed from these 20 symbols. Henceforth, the term genetic
string will incorporate protein strings along with DNA strings and RNA strings.
The R... |
from typing import Dict
from fastapi.testclient import TestClient
import pytest
from konoha.api.server import create_app
app = create_app()
client = TestClient(app)
@pytest.mark.parametrize(
"tokenizer_params", [
{"tokenizer": "mecab"},
{"tokenizer": "sudachi", "mode": "A"},
{"tokenize... |
# Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program.
user = str(input("Please provide a loginname: "))
unlock_user = str()
password = str(input("Please provide your password: "))
unlock_pw = str()
lock = str()... |
import pandas as pd
import numpy as np
import torch
def min_max_x(x):
for index, col in enumerate(x.T):
min_col = np.min(col)
max_col = np.max(col)
if min_col != max_col:
x.T[index] = (x.T[index] - min_col)/(max_col - min_col)
else:
x.T[index] = x.T[index] - min_col
return x
def load_dataset(path='./... |
from pytorch_transformers import BertTokenizer, BertForMaskedLM
import torch
import random
import numpy as np
from pytorch_transformers import BertTokenizer, BertForMaskedLM
import nltk
import argparse
import string
torch.manual_seed(0)
np.random.seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.b... |
import fcntl
import ctypes
from .base import DrmObject, DrmMode
from .drm_h import DRM_IOCTL_MODE_GETCONNECTOR
from .drm_mode_h import DrmModeGetConnectorC, DrmModeModeinfoC, drm_connector_type_id_name, DRM_MODE_OBJECT_CONNECTOR
# ("encoders_ptr", c_uint64),
# ("modes_ptr", c_uint64),
#... |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class LdpNotification(Base):
__slots__ = ()
_SDM_NAME = 'ldpNotification'
_SDM_ATT_MAP = {
'HeaderVersion': 'ldpNotification.header.version-1',
'HeaderPduLengthinOctets': 'ldpNotification.header.pduLengthinOcte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.