content stringlengths 5 1.05M |
|---|
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torchsummary import summary
# Device configuration
device = torch.device('cuda: 0' if torch.cuda.is_available() else 'cup')
print(device, torch.__version__)
# Hyper parameters
num_epo... |
from queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]
def best_first_search(source, target, n):
visited = [0] * n
visited[0] = True
pq = PriorityQueue()
pq.put((0, source))
while pq.empty() == False:
u = pq.get()[1]
# Displaying the path having lowest ... |
#!/usr/bin/python3
from demo_utils.learning import get_model
import time
import json
from demo_utils.general import gamest
from demo_utils.general import get_label
from sklearn.model_selection import GridSearchCV
# Aquí está lo necesario para realizar un expeimento
def cross_validate(model, tunning_params, data_tra... |
from application.models.models import BusinessModel, ExerciseModel, SurveyModel, InstrumentModel
def query_exercise_by_id(exercise_id, session):
return session.query(ExerciseModel).filter(ExerciseModel.exercise_id == exercise_id).first()
def query_business_by_ru(ru_ref, session):
return session.query(Busine... |
from views import *
from lookups import *
import requests
import re
from utils import *
import itertools
from config import config
if config.IMPORT_PYSAM_PRIMER3:
import pysam
import csv
#hpo lookup
import random
from flask import Response, request
import os
from werkzeug.datastructures import Headers
import re
@a... |
import os
import io
import json
import random
import uuid
from collections import defaultdict, Counter
from annoy import AnnoyIndex
from tqdm import tqdm
from itertools import product
import wcag_contrast_ratio as contrast
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from scipy.stats import mode
from ... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import json
from datetime import datetime
from functools import partial
from typing import Any
from aiohttp import web
from sqlalchemy import select
from tglib.clients import APIServiceClient, MySQLClient
from .models import TopologyHisto... |
#!usr/bin/python
# -*- coding:utf8 -*-
class UserModel(object):
users = {
1: {'name': 'zhang', 'age': 10},
2: {'name': 'wang', 'age': 12},
3: {'name': 'li', 'age': 20},
4: {'name': 'zhao', 'age': 30},
}
@classmethod
def get(cls, user_id):
return cls.users[user_... |
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/vector for details.
import numpy
import pytest
import vector._backends.numpy_
import vector._backends.object_
... |
import argparse
from data.dataset import *
from model.network import *
from model.representation import *
from training.train import *
tf.random.set_random_seed(1950)
random.seed(1950)
np.random.seed(1950)
def parse_model(name):
ind_str = name.split("_")[1]
ind = [int(i) for i in ind_str]
return ind
d... |
from worms import *
from worms.data import poselib
from worms.vis import showme
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from time import perf_counter
import sys
import pyrosetta
def main():
pyrosetta.init('-corrections:beta_no... |
# -*- coding: utf-8 -*-
"""
requests-toolbelt
=================
See http://toolbelt.rtfd.org/ for documentation
:copyright: (c) 2014 by Ian Cordasco and Cory Benfield
:license: Apache v2.0, see LICENSE for more details
"""
from .adapters import SSLAdapter, SourceAddressAdapter
from .auth.guess import GuessAuth
from ... |
# -*- coding: utf-8 -*-
__author__ = 'Marcin Usielski, Michal Ernst'
__copyright__ = 'Copyright (C) 2018-2019, Nokia'
__email__ = 'marcin.usielski@nokia.com, michal.ernst@nokia.com'
import abc
import six
from moler.event import Event
from moler.cmd import RegexHelper
@six.add_metaclass(abc.ABCMeta)
class TextualEve... |
from __future__ import print_function
import argparse
from dataset import CarvanaDataset
from net import CarvanaFvbNet
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torch.optim as optim
from torch.autograd import Variable
parser = argparse.ArgumentParser(description='Carva... |
# -*- coding: utf-8 -*-
"""This module implements regularized least square restoration methods
adapted to 3D data.
The two methods it gathers are
* **Cosine Least Square (CLS) algorith**,
* **Post-LS Cosine Least Square (Post_LS_CLS) algorithm**.
"""
import time
import numpy as np
import numpy.linalg as lin
from .... |
# !/usr/bin/env python
# coding:utf-8
# Author:XuPengTao
# Date: 2020/4/25
from ssd.config import cfg
from ssd.modeling.detector import build_detection_model
import os
obtain_num_parameters = lambda model: sum([param.nelement() for param in model.parameters()])
def model_size(model):#暂时不能处理最后层量化情况
backbone=model.ba... |
dic = {
1 : 4,
2 : 4.5,
3 : 5,
4 : 2,
5 : 1.5,
}
custos = 0
a = [int(x) for x in input().split()]
custos += dic[a[0]]
custos *= a[1]
print("Total: R$ {:0.2f}".format(custos)) |
import discord
from discord.ext import commands
import os
import aiohttp
import json
from random import choice
class Pictures(commands.Cog):
""" Category for getting random pictures from the internet. """
def __init__(self, client: commands.Bot) -> None:
""" Class init method. """
self.client... |
import emoji
import tempfile
from time import sleep
from functools import wraps
import random
import string
from typing import Callable
import telegram
import shutil
from django.conf import settings
from telegram.error import RetryAfter, NetworkError
from telegram import Bot
from app.conference.models import Slide
from... |
def bubble_sort(arr):
for i in range(len(arr)):
swap = False
for j in range(len(arr)-1-i):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
swap=True
if swap==False:
break
return arr
array=[8,5,2,4,3,2]
print(bu... |
from rest_framework import serializers
from .UbicacionSerializer import UbicacionSerializer
from .HorarioSerializer import HorarioSerializer
from sucursal_crud_api.models import Sucursal, Ubicacion, Horario
class SucursalSerializer(serializers.ModelSerializer):
ubicacion = UbicacionSerializer()
disponibilidad ... |
# -*- coding: utf-8 -*-
from app.HuobiAPI import HuobiAPI
from app.authorization import api_key,api_secret
from data.runBetData import RunBetData
from app.dingding import Message
from data.calcIndex import CalcIndex
import time
binan = HuobiAPI(api_key,api_secret)
runbet = RunBetData()
msg = Message()
index = CalcInd... |
# Copyright 2019-present NAVER Corp.
# CC BY-NC-SA 3.0
# Available only for non-commercial use
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
from nets.sampler import FullSampler
class CosimLoss (nn.Module):
""" Try to make the repeatability repeatable from one image to the other.... |
import subprocess
from os.path import join
prefix = "../split/results/"
targets = [
"mergepad_0701_2018/",
"mergepad_0701_2019/",
"mergepad_0701_2020/",
"mergepad_0701_2021/",
"mergepad_0701_2022/",
"mergepad_0701_2023/",
"mergepad_0701_2024/",
"mergepad_0701_2025/",
"mergepad_0701_2026/",
"mergepad_0701_2027/",
"merge... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.8'
_lr_method = 'LALR'
_lr_signature = '1C5696F6C19A1A5B79951B30D8139054'
_lr_action_items = {'OP_ADD':([11,],[18,]),'OP_SUB':([11,],[19,]),'LPAREN':([0,1,4,6,7,9,10,12,13,14,15,16,18,19,20,21,22,23,24,26,27,28,29,30,31,32,33,35... |
# SCH1001.sh --> JB_PARTNER_DETAILS.py
#**************************************************************************************************************
#
# Created by : Vinay Kumbakonam
# Modified by : bibin
# Version : 1.1
#
# Description :
#
# 1. Reads the 'Partner Summary' worksheet from partner detail... |
#!/usr/bin/env python2.7
from numpy import *
from pylab import *
from matplotlib import rc, rcParams
trie = genfromtxt('../data/trie_search_found.output')
tst = genfromtxt('../data/tst_search_found.output')
radix = genfromtxt('../data/radix_search_found.output')
_map = genfromtxt('../data/map_search_found.output')
u... |
""" ThirdParty's """
from .LSUV import LSUVinit
# minor changes to avoid warnings
del LSUV
|
__all__ = [
"configuration",
"persistence",
]
|
import argparse
import os
import pickle as pk
import torch
with open('../data/corr_networks/yearly_dict.pk', 'rb') as handle:
yearly_dict = pk.load(handle)
def parameter_parser():
"""
A method to parse up command line parameters.
"""
parser = argparse.ArgumentParser(description="Run SSSNET.")
... |
# Given a non-empty array of non-negative integers nums,
# the degree of this array is defined as the maximum frequency of any one of its elements.
# Your task is to find the smallest possible length of a (contiguous) subarray of nums,
# that has the same degree as nums.
import pytest
class Solution:
def findSho... |
# -*- coding: utf-8 -*-
# Standard Library
import re
# Cog Dependencies
from redbot.core import commands
class GuildConverterAPI(commands.Converter):
async def convert(self, ctx: commands.Context, argument: str):
guild_raw = argument
target_guild = None
if guild_raw.isnumeric():
... |
# Generated by Django 3.1.3 on 2020-12-05 20:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('type', '0003_remove_product_product_type'),
]
operations = [
migrations.RemoveField(
model_name... |
from datetime import datetime
import pytz
from commcare_cloud.alias import commcare_cloud
from commcare_cloud.cli_utils import ask
from commcare_cloud.colors import color_notice
from commcare_cloud.commands.deploy.sentry import update_sentry_post_deploy
from commcare_cloud.commands.deploy.utils import (
record_de... |
import re
import logging
logger = logging.getLogger(__name__)
def interpolate_text(template, values):
if isinstance(template, str):
# transforming template tags from
# "{tag_name}" to "{0[tag_name]}"
# as described here:
# https://stackoverflow.com/questions/7934620/python-dots-in... |
import os
import codecs
import logging
import json
from collections import namedtuple
from django.utils.datastructures import MultiValueDict as MultiDict
from django.conf import settings
from django.utils.http import urlencode
from django.core.urlresolvers import reverse
import datetime
from dateutil import parser
f... |
import math
import matplotlib.pyplot as plt
import matplotlib.colors as mplib_colors
import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
import io
from . import helpers as h
#
# HELPERS
#
INPUT_BANDS=[0]
DESCRIPTION_HEAD="""
* batch_index: {}
* image_index: {}
"""
DESCRIPTION_HIST="""{}
... |
from __future__ import annotations
import json
import sys
from datetime import datetime
from typing import Any, List, Optional
from meilisearch.client import Client
from meilisearch.errors import MeiliSearchApiError
from rich.console import Group
from rich.panel import Panel
from rich.traceback import install
from ty... |
import heapq
import operator
import os
from bitstring import BitArray
import json
import pickle
import codecs
DIR_DATA = "media/"
DIR_HUFFMAN = DIR_DATA
#using to save dictionary
temp_reverse = {}
#init a seperate sympol as Node of Huffman Tree with value = frequency
class Node:
#build a class node with sympol, fr... |
from flask import jsonify, g
from app import db
from app.api import bp
from app.api.auth import auth_tp
@bp.route('/tokens', methods=['DELETE'])
@auth_tp.login_required
def revoke_token():
g.current_user.revoke_token()
db.session.commit()
return '', 204
|
from . import discord
from . import log # noqa
def main():
"""Run discurses."""
client = discord.DiscordClient()
client.run()
if __name__ == '__main__':
discurses.main()
|
from . import models
from . import routes
from . import db_session
from . import app
|
import pyPdf
import time
import urllib2
from django.conf import settings
#save file locally
def archive_file(original_url, gov_id, doc_type, file_type):
type_dir = doc_type.lower().replace(' ', '_')
file_name = "%s%s/%s.%s" % (settings.DATA_ROOT, type_dir, gov_id, file_type)
try:
remote_file = url... |
# -*- coding: utf-8 -*-
# @author: Optimus
# @since 2018-12-15
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_index_map = {}
for index, num in enumerate(nums):
if num in num_... |
#!/usr/bin/env python3
# coding:utf-8
import os, shutil
def fun(addr):
items = os.listdir(addr)
for each in items:
if os.path.isfile(each): # 是文件,返回 True;是目录,返回 False
item = os.path.splitext(each)[0]
name = item.split("-")[0] # 文件名分割,获取 ... |
"""TRAINING
Created: May 04,2019 - Yuchong Gu
Revised: May 07,2019 - Yuchong Gu
"""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import time
import logging
import warnings
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from ... |
import pathlib
import re
import sys
import setuptools
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .feedback import Feedback
class SearchResultFeedback(Feedback):
"""
Database model representing feedback about search results (e.g. empty results).
"""
search_query = models.CharField(max_length=1000, verbose_n... |
name = "wiki_archive"
|
#!/usr/bin/env python
"""
.. module:: converters
:synopsis: Converters for handling various types of content.
"""
import docutils
import docutils.core
import markdown
import os
content_types = ["markdown", "ReST"]
# Content converters.
def convertMDtoHTML(markdown_text):
return markdown.markdown(markdown_text... |
import logging
def get_logger():
logger = logging.getLogger("ddns_server")
logger.setLevel(logging.INFO)
log_file = logging.FileHandler("log.log")
log_file.setLevel(logging.INFO)
log_stream = logging.StreamHandler()
log_stream.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asc... |
import imagehash
import pandas as pd
import os
from PIL import Image
from collections import defaultdict
from square_crop import square_crop
directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego_images/'
data_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/image_hashes_2.csv'
data_... |
#!/usr/bin/python
# Import the CGI module
import MySQLdb
import cgi
import cgitb
cgitb.enable()
# Test with: http://192.168.0.100:8000/cgi-bin/AddingDataXml.py?operanda=2&operandb=3&answer=5
# Required header that tells the browser how to render the HTML.
def getHeader():
return """Content-Type: text/xml\n
<?xml ... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
from myuw.dao.registration import get_schedule_by_term
from myuw.dao.instructor_schedule import get_instructor_schedule_by_term
from myuw.dao.term import get_current_quarter, get_current_summer_term
from myuw.dao.buil... |
#coding:utf-8
import scapy_http.http as HTTP
from scapy.all import *
from scapy.error import Scapy_Exception
import time
import re
import os
from xmlrpclib import ServerProxy
count=0
pt = re.compile('(GET|POST).*(HTTP)')
ag = re.compile('(User-Agent:).*')
s = ServerProxy("http://localhost:8888")
def getURL(data):
u... |
# coding=utf-8
import unittest
from rozipparser.codeparser import CodeParser
class TestSmallLocalityParsing(unittest.TestCase):
def test_number_of_codes(self):
parser = CodeParser("rozipparser/tests/inputs/small_locality_input.xlsx")
codes = parser.get_codes()
self.assertEqual(len(codes... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class VideoCategory(object):
"""
NOTE: This class is au... |
import cv2
import numpy as np
img = cv2.imread('prof.jpeg', cv2.IMREAD_COLOR)
img = cv2.resize(img, (500, 500))
# perfom a filter with a kernel
# its like blurring it removes edges and averages
blur1 = cv2.blur(img, (3,3))
# well in this case they are the same
# Gaussian filter creation cv2.getGaussianKer... |
from django import template
from ..models import Category
register = template.Library()
@register.simple_tag
def title():
return 'وبلاگ جنگویی'
@register.simple_tag
def brand_name():
return 'جنگو وب'
@register.inclusion_tag('blog/partial/category_navbar.html')
def category_navbar():
return {
'ca... |
import random
def generate_email():
prefix = 'ak' + str(''.join([random.choice(list('qwertyuio')) for x in range(5)]))
return f"{prefix}@mail.ru"
def generate_name():
prefix = 'Pug_' + str(''.join([random.choice(list('123456789')) for x in range(2)]))
return prefix
def test_login(app):
admin_f... |
# coding: utf-8
################################################################################
# CS 224W (Fall 2017) - HW1
# Code for Problem 1
# Author: luis0@stanford.edu
# Last Updated: Oct 8, 2017
################################################################################
import snap
import numpy as np
impo... |
import os
def cpr(parentFile, pasteDir, names):
parentFileContent = open(parentFile, "rb").read()
extension = os.path.splitext(parentFile)[1]
for name in names:
name = str(name)
currentDir = os.path.join(pasteDir, name)+extension
currentFile = open(currentDir, "wb")
currentFile.write(parentFileCont... |
import time
import bisect
import dgl
import torch
import numpy as np
from tqdm import tqdm
# Count motif 1
def count_motif_1_1(g, threshold_time, eid):
src, dst = g.find_edges(eid)
if not g.has_edges_between(dst, src):
return
src_out_timestamp = g.edata['timestamp'][g.out_edges(src, form='eid')]
src_out_... |
# coding: utf8
from pycropml.transpiler.main import Main
source = u"""def test(int a):
cdef list g=[14,15,12,12]
cdef int i
a=12
for i in g:
a=a+i
return a
"""
output_cs=u"""using System;
using System.Collections.Generic;
public class Program
{
static in... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you m... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-10-16 07:07
from __future__ import unicode_literals
from django.db import migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('cart', '0005_auto_20180111_0700'),
]
operations = [
migrati... |
from tkinter import *
import sys
# Medicine Menu
def mclickedbtn1():
print("Hello")
def mclickedbtn2():
print("Hello")
def mclickedbtn3():
print("Hello")
def mclickedbtn4():
print("Hello")
def clickedbtn1():
medicine_menu_window = Tk()
medicine_menu_window.geometry('350x200')
medicine_menu_w... |
# coding: utf-8
# # Explore offset vector
#
# We want to know what the offset vector is capturing. Theoretically it should be capturing the "essence of gene A" since it is defined by taking the samples with the highest expression of gene A and the lowest expression of gene A.
#
# We want to test if this offset vec... |
import os
import platform
import click
import kungfu.yijinjing.journal as kfj
import pyyjj
@click.group(invoke_without_command=True)
@click.option('-H', '--home', type=str, help="kungfu home folder, defaults to APPDATA/kungfu/app, where APPDATA defaults to %APPDATA% on windows, "
... |
#!/usr/bin/env python
# coding: utf-8
# # Gaussian Mixture Model
#
# GMM runs on 5 features by default: beam, gate, time, velocity, and spectral
# width. It performs well overall, even on clusters that are not well-separated
# in space and time. However, it will often create clusters that are too high
# varian... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-12-05 07:47
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0055_merge_20171205_0847'),
]
operatio... |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["AuditEventSourceType"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class AuditEventSourceType:
"""
Audit Event Source Type
The type of proces... |
from fastapi_tag.base import model
__all__ = ["model"]
|
#!/usr/bin/env python
"""
plot energy usage by PM jobs
"""
__author__ = "Jan Balewski"
__email__ = "janstar1122@gmail.com"
import numpy as np
import time
from pprint import pprint
from toolbox.Plotter_Backbone import Plotter_Backbone
from toolbox.Util_IOfunc import read_one_csv
from toolbox.Util_Misc import smooth... |
# -*- coding: utf-8 -*-
# =============================================================================
# MIT License
#
# Copyright (c) 2018 Charles Jekel
#
# 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... |
# Script to get the system's info
from __future__ import print_function
import platform
import multiprocessing as mp
'''
Functions:
------------------------------------------------------
sysinfo(display = True, return_info = False)
Gets the details about the system
----------------------------... |
import LevelBuilder
from sprites import *
def render(name,bg):
lb = LevelBuilder.LevelBuilder(name+".plist",background=bg)
lb.addObject(Hero.HeroSprite(x=42, y=245,width=32,height=32))
lb.addObject(Beam.BeamSprite(x=42, y=287,width=17,height=14,angle='0',restitution=0.2,static='true',friction=0.5,density=20... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class UnsupportedPythonError(Exception):
pass
__minimum_python_version__ = "3.6"
if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))):
raise UnsupportedPythonError(f"pyvib does not support Python < {__minimum_pytho... |
# Generated by Django 2.1.5 on 2019-02-07 23:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hyperion', '0003_userprofile_url'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='github',
... |
import random
from evennia import TICKER_HANDLER
from evennia import CmdSet, Command, DefaultRoom
from evennia import utils, create_object, search_object
from evennia import syscmdkeys, default_cmds
from evennia.contrib.text_sims.objects import LightSource, TutorialObject
# the system error-handling module is defined... |
#coding=utf8
import itchat
import re
import sys
from itchat.content import *
global author
global isDisturbOn
global visit
global username
def messageProccess(msg):
if not msg["FromUserName"] == author:
if msg["Type"] == "Text":
if re.search("#sinon", msg["Text"]) == None:
if i... |
import os
from setuptools import setup
from gitissius import gitissius
setup(
name = "Gitissius",
version = gitissius.VERSION,
author = "Giorgos Logiotatidis",
author_email = "seadog@sealabs.net",
description = "Distributed bug tracking for Git.",
license = "Mixed",
keywords = "bug, tracki... |
"""
Plot ENSO from 2015-2018 using daily oisstv2
Data : 18 March 2018
Author : Zachary M. Labe
"""
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import datetime
import cmocean
### Directory and time
directoryfigure = './Figures/'
directorydat... |
# -*- coding: utf-8 -*-
"""
Guney's network proposed in A Deep Neural Network for SSVEP-based Brain-Computer Interfaces.
Modified from https://github.com/osmanberke/Deep-SSVEP-BCI.git
"""
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base import compute_... |
import numpy as np
import itertools
import torch
class TestAugmentor(object):
"""Test Augmentor.
Args:
mode (str): inference mode ('min', 'max', 'mean').
num_aug (int): number of data augmentations: 4-fold, 16-fold
"""
def __init__(self, mode='min', num_aug=4):
self.mode = mode... |
"""
Cciss - Files ``/proc/driver/cciss/cciss*``
===========================================
Reads the ``/proc/driver/cciss/cciss*`` files and converts them into a
dictionary in the *data* property.
Example:
>>> cciss = shared[Cciss]
>>> cciss.data['Logical drives']
'1'
>>> 'IRQ' in cciss.data
True... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
import logging
import os
import errno
from .BaseDispatch import BaseDisp... |
from nintendo import account
api = account.AccountAPI()
pid = api.get_pid("Kinnay-WiiU")
mii = api.get_mii(pid)
print("NNID:", mii.nnid)
print("PID:", pid) #Same as mii.pid
print("Name:", mii.name)
info = mii.data
print("Mii:")
print("\tBirthday: %i-%i" %(info.birth_day, info.birth_month))
print("\tCreator name:", i... |
from unittest.mock import patch
from pytest import fixture
@fixture(autouse=True)
def environ():
environ = {
"slack_access_token": "slack-access-token",
"slack_signing_secret": "slack-signing-secret",
}
with patch.dict("os.environ", environ, clear=True):
yield environ
@fixture
d... |
import cv2
import numpy as np
from operator import floordiv
vc = cv2.VideoCapture(0)
cv2.namedWindow("top")
cv2.namedWindow("bottom")
if vc.isOpened():
rval, frame = vc.read()
height = len(frame)
width = len(frame[0])
else:
rval = False
lights = (16,9)
history = 5
top = np.zeros((lights[0], 1,... |
"""
If you use this code, please cite one of the SynthSeg papers:
https://github.com/BBillot/SynthSeg/blob/master/bibtex.bib
Copyright 2020 Benjamin Billot
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 Lice... |
"""Multiply SOIL13 and SOIL14 by 10 to change units from % to g/kg"""
import pyiem.cscap_utils as util
def main():
"""Go Main Go"""
config = util.get_config()
spr_client = util.get_spreadsheet_client(config)
drive = util.get_driveclient(config)
# Fake last conditional to make it easy to reproces... |
##!/usr/bin/python
import numpy as np
import pylab as plt
import seaborn as sns
sns.set_context('poster')
plt.subplot(1,1,1)
data = np.genfromtxt(fname='energy.dat')
#data = np.loadtxt('traj.dat')
#for x in range(1,data.shape[-1]):
plt.plot(data[:,0],data[:,1],label='kinetic')
plt.plot(data[:,0],data[:,2],label='p... |
import nxutils
import networkx as nx
# TODO: Update this to remove dependency on static zipcode
# if we ever need to use this code
zipCode = '02138'
prefix = 'neighborhood'
n = nxutils.NXUtils(prefix, zipCode)
n.buildNetwork()
DG = n.getNetwork()
fullCycles = nx.simple_cycles(DG)
print('Number of cy... |
# This file was auto generated; Do not modify, if you value your sanity!
import ctypes
try: # 2
from can_settings import can_settings
from swcan_settings import swcan_settings
except:
from ics.structures.can_settings import can_settings
from ics.structures.swcan_settings import swcan_settings
# flags
... |
"""Optimization methods."""
|
# -*- coding: utf-8 -*-
"""Build functions to wrap mlflow models.
Existing implementation returns a synchronous/blocking function. This decision
was taken because applying ML models is probably CPU-bound. Not having
unnecessary asynchronous code also makes testing simpler.
Current supports only the pyfunc flavour.
C... |
# Generated by Django 4.0.2 on 2022-02-04 17:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='products',
old_name='product_type',
... |
"""
Copyright 2019 IBM 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 writing, software... |
# Copyright (c) 2019 PaddlePaddle 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 appli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.