content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""Node redundancy for bipartite graphs."""
# Copyright (C) 2011 by
# Jordi Torrents <jtorrents@milnou.net>
# Aric Hagberg <hagberg@lanl.gov>
# All rights reserved.
# BSD license.
from __future__ import division
from itertools import combinations
from networkx import NetworkXErr... |
"""Public classes of the terrainbento package.
terrainbento has five types of public classes: base models, derived models
precipitators, runoff-generators, and boundary condition handlers. Base models
are used to help easily build new models. Derived models are models that have
inherited from the **ErosionModel** base... |
import ast
class AnalyzerException(Exception):
pass
class AnalyzerVisitException(AnalyzerException):
def __init__(self, node: ast.stmt):
self.node = node
super().__init__(
f"Unexpected error when analyzing '{type(node).__name__}' statement at "
f"{node.lineno}:{node.c... |
from . import classifier
__version__ = "0.1.0.dev"
__all__ = [
'classifier'
] |
#! /usr/bin/python3
"""a script symulating the card game 'War''"""
#card: suit,rank,value
from random import shuffle
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4,... |
#!/usr/bin/env python
import sys
import logging
import csv
import libs.config_loader
import libs.processwords
from libs.anki_importer import import2cards
from libs.kindleimporter import KindleImporter
def main():
config = libs.config_loader.load_config()
kindle_importer = KindleImporter(config)
# Step ... |
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
EDAM_NOTE_SOURCE_WEB_CLIP = "web.clip"
EDAM_NOTE_SOURCE_MAIL_CLIP = "mail.clip"
EDAM_NOTE_SOURCE_MAIL_SMTP_GATEWAY = "mail.smtp"
|
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
|
#Decorators
'''
Implementing decorators in different
functions
'''
def decor(func):#1st decorator
'''
main function calling another function
'''
def wrap():
'''
wraping up function
'''
print("====================")
func()
print("====================")
... |
# Copyright 2016, 2017 California Institute of Technology
# Users must agree to abide by the restrictions listed in the
# file "LegalStuff.txt" in the PROPER library directory.
#
# PROPER developed at Jet Propulsion Laboratory/California Inst. Technology
# Original IDL version by John Krist
# Python t... |
from amino.test.spec_spec import Spec
from amino import Map, Empty, Just, _, Right, Either
class MapSpec(Spec):
def lift(self):
key = 'key'
val = 'value'
m = Map({key: val})
m.lift(key).should.equal(Just(val))
m.lift(key + key).should.equal(Empty())
def add(self):
... |
import os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import git
from a2c.a2c import A2C
from a2c.callback import ProgressBarCallback
from environments.continuous_teaching import ContinuousTeaching
from environments.discontinuous_teaching import DiscontinuousTeaching
from environments i... |
expected_output = {
"tloc_path": {
"10.220.100.10": {"tloc": {"default": {"transport": "ipsec"}}},
"10.220.100.20": {"tloc": {"default": {"transport": "ipsec"}}},
"10.220.100.30": {"tloc": {"default": {"transport": "ipsec"}}},
}
}
|
from pdf import pdf_parser
import os
from pathlib import Path
def test_parse_pdf_no_debug(mocker):
path = Path(os.getenv('PYTHONPATH'))
pdf_file = os.path.join(path, "tests/data/test.pdf")
stats = [0, 0]
pages = pdf_parser.parse_pdf(pdf_file, False, stats)
assert pages != None
def test_parse_pdf_w... |
# Macaroon - a desktop macro tool
# Copyright (C) 2007 Eitan Isaacson <eitan@ascender.com>
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty;... |
from random import randint
import numpy as np
import matplotlib.pyplot as plt
class AddAndSubImage:
def __init__(self, image):
self.image = image
def create_and_show_img(self):
# Generate random number from 0 to 255
random_value = randint(0, 256)
# Transform pixels
i... |
# Copyright (C) 2014 Universidad Politecnica de Madrid
#
# 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... |
# Generated by nuclio.export.NuclioExporter
import pandas as pd
import pyhive
from sqlalchemy.engine import create_engine
from mlrun.execution import MLClientCtx
def sql_to_file(
context: MLClientCtx,
sql_query: str,
database_url: str,
file_ext: str = "parquet",
) -> None:
"""SQL Ingest - Ingest ... |
#A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
#
#The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
#
#How many possible unique paths are there?
cl... |
# Generated by Django 3.2.11 on 2022-02-09 09:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feeds', '0004_alter_feed_image'),
]
operations = [
migrations.AlterField(
model_name='item',
name='status',
... |
# -*- coding: utf-8 -*-
"""
cron: 45 5 * * *
new Env('哔咔漫画');
"""
import hashlib
import hmac
import json
import random
import string
import time
import requests
from notify_mtr import send
from utils import get_data
class Picacomic:
def __init__(self, check_items):
self.check_items = check_items
@... |
""" Command Line entry point.
"""
import sys
import logging
import textwrap
import csv
import os
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
import pkg_resources
from prettytable import PrettyTable
import dicom4ortho.defaults as defaults
import dicom4ortho.controller as contr... |
"""cognito-login"""
VERSION = '0.0.2'
NAME = 'cognito-login'
AUTHOR = 'Trek10, Inc'
AUTHOR_EMAIL = 'package-management@trek10.com'
DESCRIPTION = 'cognito-login - A CLI to get a jwt from cognito login credentials'
LICENSE = 'MIT'
HOMEPAGE = 'https://github.com/trek10inc/cognito-login'
MESSAGE = 'Thanks for using cogni... |
# Generated by Django 3.0.2 on 2020-03-01 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0008_eheadline_source'),
]
operations = [
migrations.AddField(
model_name='sheadline',
name='source',
... |
def get_answer():
"""Get an answer."""
return True |
def solution(_max):
# Type your solution here
dp = [0]*_max
fb = [0]*_max
if _max == 1:
return 0
if _max == 2:
return 2
fb[0], fb[1] = 1, 2
dp[0], dp[1] = 0, 2
i = 2
while i < _max:
fb[i] = fb[i-1]+fb[i-2]
if fb[i] % 2 == 0:
dp[i] = f... |
# coding=utf-8
import os
import unittest
from mock import patch
from ddt import ddt, data
from digestparser.objects import Digest
from provider import digest_provider, download_helper
from activity.activity_CopyDigestToOutbox import (
activity_CopyDigestToOutbox as activity_object,
)
import tests.activity.settings... |
import time
import numpy as np
import acc_image_utils as acc
original_size = 4096
new_size = (1024,1024)
sigma = original_size/3
n1y,n1x = np.mgrid[0:original_size,0:original_size]
n1 = (((n1y - (0.5*original_size))/sigma)**2) + (((n1x - (0.5*original_size))/sigma)**2)
n1 = np.exp(-n1)
loop_tester = 25
t1 = time.time(... |
import tkinter as tk
import tkinter.font
import os
import sys
import time
import Fusion.Khepera.Robots.vKhepera as vk
import Fusion.Core.Reactor as fusion
import Fusion.Gui.GuiTypes as gt
import importlib
def insterr(code):
try:
x = y
except Exception as inst:
print(type(inst)) # the exception instance
... |
import pymongo
from scrapy import signals
from scrapy.exceptions import IgnoreRequest
class PortaisTechDownloaderMiddleware(object):
urls_distinct = set()
@classmethod
def from_crawler(cls, crawler):
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
... |
from ..utils import Object
class GetAccountTtl(Object):
"""
Returns the period of inactivity after which the account of the current user will automatically be deleted
Attributes:
ID (:obj:`str`): ``GetAccountTtl``
No parameters required.
Returns:
AccountTtl
Raises:
... |
# enable logger
import logging
import cv2
from .TableInputStream import TableInputStream
logger = logging.getLogger(__name__)
class OpenCVCameraTIS(TableInputStream):
camera = None
def __init__(self, config, board, usestream):
try:
self.camera = cv2.VideoCapture(config.get("camera", "... |
from .entities import RectangleEntity, CircleEntity
from .geometry import Point
# For colors, we use tkinter colors. See http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
class Car(RectangleEntity):
def __init__(self, center: Point, heading: float, color: str = 'red'):
size = Point(4., 2.)
... |
import logging
import tkinter
from tkinter import ttk, font as font, messagebox, _setit
from typing import Union, List, Tuple, Dict, Mapping
import mouse
import lifxlan
import win32api
from lifxlan import (
ORANGE,
YELLOW,
GREEN,
CYAN,
BLUE,
PURPLE,
PINK,
WHITE,
COLD_WHITE,
WAR... |
import unittest
from zoo import *
class TestSpecies(unittest.TestCase):
def test_common_name_empty_string_by_default(self):
species = Species()
self.assertEqual(species.common_name, '')
def test_georegion_empty_string_by_default(self):
species = Species()
self.assertEqual(species.geo_region, '')
if __name... |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from MatplotlibWidget import MatplotlibWidget
class TableWidget(QTableWidget):
def __init__(self, parent, data, headTitle, xcol, ycol):
super(TableWidget, self).__init__(parent)
self.father = parent
... |
from django.forms import ModelForm
from catalog.models import ItemTemplate
class ItemTemplateForm(ModelForm):
class Meta:
model = ItemTemplate
#fields = ['pub_date', 'headline', 'content', 'reporter']
exclude = ("property_number", )
|
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from ai.utils.antivirus import AVException
from .scanner import AVScanner
av_scanner = AVScanner()
USE_SCANNER = settings.ANTIVIRUS_ENABLED if hasattr(settings, 'ANTIVIRUS_ENABLED') else True
class AVFileSystemStora... |
import pytest
from Anomali_Enterprise import *
def test_domain_command_benign(mocker):
"""
Given:
- a domain
When:
- mocking the server response for a benign domain, running domain_command
Then:
- validating that the domain score is unknown
- validating the returned c... |
"""Package constants."""
# pylint: disable=too-few-public-methods
from enum import IntEnum
class ColorSpace(IntEnum):
"""Color space specifier."""
SRGB = 1
"sRBG"
UNCALIBRATED = 0xFFFF
"Uncalibrated or Other"
class ExifMarkers:
"""EXIF marker segments bytes."""
SEG_PREFIX = "FF"
... |
"""
Functions and operations for tensor algebra
Credit to `Jean Kossaifi <http://jeankossaifi.com/>`_.
"""
import functools
import numpy as np
# TODO: I think it will be better if the following three operations would have the same signature
def khatri_rao(matrices, skip_matrix=None, reverse=False):
""" Khatri-R... |
#!/usr/bin/python3
import tensorflow as tf
import tfgraph
def main():
with tf.Session() as sess:
g: tfgraph.Graph = tfgraph.GraphConstructor.unweighted_random(sess, "G", 10, 85)
g_sparse: tfgraph.Graph = tfgraph.GraphConstructor.as_sparsifier(sess, g, 0.75)
print(g)
print(g.m)
print(g_sparse)... |
import unittest
from unittest import mock
from djmodels.utils.lorem_ipsum import paragraph, paragraphs, sentence, words
class LoremIpsumTests(unittest.TestCase):
def test_negative_words(self):
"""words(n) returns n + 19 words, even if n is negative."""
self.assertEqual(
words(-5),
... |
from block import Block
from blockchain import BlockChain
from transaction import Transaction
from node import Node
import hashlib
def getTestChain():
testblock = BlockChain()
test_trans = Transaction(f="master", to="0", header ="test1",value= 5)
testblock.addUnused(test_trans)
test_trans = Transaction... |
# Reformat the card_resfam_updated table to an NGLess functional_map table
import pandas as pd
import pickle
card_resfam = pd.read_table('cold/annotations/GMGC.95nr.card_resfam_updated.out.r')
for c in ['Taxid', 'Bioproject']:
assert not len(card_resfam[c].dropna())
card_resfam = card_resfam.drop(c,axis=1)
re... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class AllProductsSpider(CrawlSpider):
name = 'all_products'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/index.html']
rules = (
... |
from confluence.models.icon import Icon
import logging
from typing import Any, Dict
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class User:
"""
Represents a single user object in confluence either as attached to a page
or as requested directly over the API.
Note tha... |
#Write a program that outputs the string representation of numbers from 1 to n.
#
#But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
#
#Example:
#
#n = 15,
#
#Return:
#[
# "1",
#... |
from .api import UpStorageBucket |
#### created by Alessandro Bigiotti ####
import numpy as np
#function to normalize the prices data used by wavelet_prices_smooth
def Normalize_Data_Data_Raw(resize_data):
normal_data = []
local_min_val = 99999999999
local_max_val = -99999999999
for i in range (0, len(resize_data)-1):
if resize_data[i] > local_ma... |
"""
Authors: Kostas Stamatiou, Donnie Marino, Dan Getman, Dahl Winters, Nate Ricklin
GBDX Workflow interface.
"""
from __future__ import print_function
from builtins import object
import json
from gbdxtools.auth import Auth
from gbdxtools.s3 import S3
class Workflow(object):
def __init__(self, **kwargs):
... |
import numpy
class Mesh(object):
"""
Build a quadrilateral structured unit square mesh.
"""
def __init__(self, nx: int, ny: int):
"""
Parameters
----------
nx
The number of cells in the x direction.
ny
The number of cells in the y direct... |
import numpy as np
import torch
def get_optim(params, optim_id, lr, q_lr=None, batch_scale=True, grad_clip=None, weight_decay=None):
if optim_id is "Adam":
return Adam(
params, lr=lr, q_lr=q_lr, batch_scale=batch_scale, grad_clip=grad_clip, weight_decay=weight_decay
)
elif optim_id... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from generador_pdf.msg import Pdf
def mandaInformacion(ruta):
pub = rospy.Publisher('pdf_topic', Pdf, queue_size=10)
rospy.init_node('envia_informacion', anonymous=True)
rate = rospy.Rate(10) # 10hz
contador = 1
print "Comenzando"
... |
import unittest
from request_parsers.validators import video_jpeg_quality
class VideoJpegQualityValidationTest(unittest.TestCase):
def test_reject_integers_out_of_bounds(self):
self.assertFalse(video_jpeg_quality.validate(0))
self.assertFalse(video_jpeg_quality.validate(101))
def test_accep... |
import logging
import pandas as pd
from config import Configuration
from functools import reduce
from tasks.features.base import FeatureTask
from tasks.features.page import NameSpacesFeature
from tasks.features.page import UserPageEditsFeature
from tasks.features.page import TotalEditedPagesFeature
from tasks.feature... |
import unittest
class StateTestCase(unittest.TestCase):
CLASS = None
def setUp(self):
if self.CLASS is None:
raise unittest.SkipTest("Base class not tested")
self.start_state = (False, 0)
def test_should_ignore_disabled_game(self):
self.assertEqual(self.CLASS().move('... |
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.urls import reverse
def logout_view(request):
logout(request)
return redirect(reverse('home'))
|
# this file was generated using test/python/sample/generate.py
# python
import io
import pathlib
# pytest
import pytest
# woosh
import woosh
def tokenize_file_like(source):
return list(woosh.tokenize(io.BytesIO(source)))
def tokenize_bytes(source):
return list(woosh.tokenize(source))
SAMPLE_DIR = pathlib.P... |
from os.path import join
import pathlib
import numpy as np
def _is_32bit():
return np.intp(0).itemsize < 8
def check_propack_submodule():
if not (pathlib.Path(__file__).parent / 'PROPACK/README').exists():
raise RuntimeError("Missing the `PROPACK` submodule! Run "
"`git s... |
from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.views.generic import (ListView,UpdateView)
from .forms import EventForm
from .models import Event
import os
# Create your views here.
def index(request):
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
newspa... |
# Python3 implementation of the approach
# Function to return the number
# of sub-strings that do not contain
# the given character c
def countSubstrings(s, c):
# Length of the string
n = len(s)
cnt = 0
Sum = 0
# Traverse in the string
for i in range(n):
# If current character is different
# fr... |
from contextlib import contextmanager
from typing import List, Dict
import random
from paragen.criteria import create_criterion
from paragen.models import create_model
from paragen.tasks import register_task
from paragen.tasks.base_task import BaseTask
from paragen.generators import create_generator
from paragen.utils... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: @manojpandey
# Last modified: Jun 26, 2017 20:31:06
from bs4 import BeautifulSoup
import requests
import sys
import argparse
class FbFinder:
@staticmethod
def find_id(url):
'''Returns the facebook user ID taking the profile URL as the input
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Placeholder for qlib-based simulator."""
|
#!/usr/bin/python
import numpy as np
import scipy.spatial.distance
import cv2
import sys, os
import math
from numpy.linalg import inv
has_yaml = False
try:
import yaml
# A yaml constructor is for loading from a yaml node.
# This is taken from: http://stackoverflow.com/a/15942429
def opencv_matrix_con... |
##########_api settings_##########
key = ''
b64secret = ''
passphrase = '' |
from unittest import TestCase
import pandas as pd
from scattertext import whitespace_nlp, CorpusFromParsedDocuments
from scattertext.test.test_corpusFromPandas import get_docs_categories
class TestParsedCorpus(TestCase):
@classmethod
def setUp(cls):
cls.categories, cls.documents = get_docs_categories()
cls.pa... |
# Code from https://github.com/quark0/darts
from collections import namedtuple
import torch
import torch.nn as nn
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
AmoebaNet = Genotype(
normal = [
('avg_pool_3x3', 0),
('max_pool_3x3', 1),
('sep_conv_3x3', 0),
('sep_con... |
import pytest
from dotmailer.campaigns import Campaign
from dotmailer.constants import constants
from dotmailer.exceptions import ErrorCampaignInvalid
def test_update_valid(sample_campaign):
new_data = {
'name': 'new name',
'subject': 'new subject',
'from_name': 'new from name',
'... |
#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import growth.model
import growth.viz
import seaborn as sns
colors, _ = growth.viz.matplotlib_style()
# Define the parameter ranges
gamma_max = 9.65
Kd_cAA = 0.025
nu_max_scenario = np.linspace(0, 5, 100)
nu_max = np.linspace(0, 5, 25)
palet... |
"""
Propagation effects.
"""
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline as ip
try:
from pyfftw.interfaces.numpy_fft import fft, ifft, rfft, irfft # Performs much better than numpy's fftpack
import pyfftw
#import scipy.signal
#scipy.signal.signaltools.fftn = pyf... |
import torch
from pathlib import Path
from PIL import UnidentifiedImageError, Image
from torch.utils.data import Dataset
class ImageTextDataset(Dataset):
def __init__(self,
preprocess,
folder,
bpe_tokenizer,
truncate_text=True,
... |
from pathlib import Path
import os
DOWNLOADS_FOLDER = Path(os.path.expanduser("~")) / Path("Downloads/")
class Filter_Configs():
MAXS = {
"size": (1920, 1080)
}
class VHS_Configs():
SIZE = (705, 405)
PATHS = {
"images": {
".": Path("./retrofy/filters/vhs/images"),
... |
from django.shortcuts import render
from . forms import bill_splitter_form
def splitter(request):
if request.method == 'POST':
form = bill_splitter_form(request.POST)
# check whether it's valid:
if form.is_valid():
amount=form['amount'].value()
amount=int(amount)
... |
# 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
# distributed under t... |
""" Node classes used by the Node Server. """
import polyinterface
import asyncio
LOGGER = polyinterface.LOGGER
class BaseNode(polyinterface.Node):
def __init__(self,
controller,
primary,
address,
name,
sb):
# Each devi... |
#!/usr/bin/env python3
# This sample script demonstrates how to
# 1. get a list of flow property expressions
# 2. create a new flow property expression
# 3. get a flow property expression by id
# 4. update an existing flow property expression
# 5. delete a flow property expression
import importlib
import json
import o... |
from logging import debug
from typy.exceptions import NoSuchAttribute, CantSetBuiltinAttribute
from typy.types import Type, Instance
from typy.builtin.functions import BuiltinFunction as Fun
class BuiltinDataInstance(Instance):
def set_attribute(self, name, value):
raise CantSetBuiltinAttribute(self)
c... |
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.utils import shuffle
import numpy as np
from utils import metrics
from sklearn.metrics import f1_score
def get_sorting_index_with_noise_from_lengths(lengths, noise_frac) :
if noise_frac > 0 :
noisy_lengths... |
"""
Extract the dominant colors from each frame in a movie.
"""
import argparse
import os
import json
import math
import subprocess
import sys
SEC_IN_MIN = 60
MIN_IN_HOUR = 60
FRAME_FILE_NAME = "frame_%d.png"
END = 159 * SEC_IN_MIN
SAMPLE_WIDTH = 1920 / 4
def ensure_dir(name):
if not os.path.exists(name):
... |
import prparseralldays
prparseralldays.parse() |
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu).
#
# 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, ... |
"""
This file provides examples how to convert odml files between versions and formats.
"""
import argparse
import sys
from os.path import join
from odml.tools import ODMLReader, ODMLWriter, RDFWriter
from odml.tools.converters import FormatConverter, VersionConverter
ROOT = "/home/msonntag/Chaos/DL/conv/"
FOLDER_OU... |
from flask import redirect, render_template, request, session, flash
from functools import wraps
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return render_template("403.html")
return f(*args, **kwargs)
return decor... |
#******************************************************************************
#
# MantaGen
# Copyright 2018 Steffen Wiewel, Moritz Becher, Nils Thuerey
#
# This program is free software, distributed under the terms of the
# Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
#*****************... |
import torch
import numpy as np
import os
import os.path as osp
from PIL import Image
from torch.utils import data
class cityscapesDataSetLabel(data.Dataset):
"""
Class to help load the Cityscapes dataset labels
"""
# for reading CS with labels
def __init__(self, root, list_path, crop_size=(11, 1... |
"""
# Project: 2D Cloth Matching Using OpenCV
# Author: Heejune Ahn (heejune@snut.ac.kr), Matiur Rahman Minar (minar09.bd@gmail.com)
# Date created: 2020-07-27
# Python version: 3.x
# Requirements: numpy, opencv-contrib-python, scikit-image, sortedcontainers
# Description: This program applies As-Rigid-As-Possible (ARA... |
import model
if __name__ == "__main__":
#import cProfile, pstats, io
#pr = cProfile.Profile()
#pr.enable()
model.checkDB()
q = model.getNextQuery()
if not q:
model.loadQuery()
q = model.getNextQuery()
print('query: %s'%q)
model.search(q)
#pr.dis... |
# 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... |
# coding=utf-8
import numpy as np
from decoder import regression_decoder
import argparse
import heapq
from utils import load_pickle,save_pickle
from sklearn.preprocessing import StandardScaler
import os
def evaluation(i1,p1,i2,p2,metric='pearson'):
#print("Cosine Similarity Calculation...")
#Normalize vectors
'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2020-04-15 23:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('survey', '0001_initial'),
]
operations = [
migrations.AddField(
... |
from lexrank.algorithms.summarizer import LexRank # noqa
from lexrank.mappings.stopwords import STOPWORDS # noqa
|
# -*- coding: utf-8 -*-
"""This module defines functions for Mechanical Stiffness calculations."""
from numbers import Integral
import numpy as np
from prody import LOGGER
from prody.utilities import checkCoords
__all__ = ['calcMechStiff', 'calcStiffnessRange', 'calcMechStiffStatistic',
'calcStiffnessR... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, Unicode
Base = declarative_base()
class Music(Base):
id = Column(Integer, primary_key=True)
name = Column(Unicode, nullable=False)
__tablename__ = 'music'
class Tag(Bas... |
(a, b, c) = map(int, input().split(' '))
numeros = [a, b, c]
numeros.sort()
print(f'{numeros[0]}\n{numeros[1]}\n{numeros[2]}\n')
print(f'{a}\n{b}\n{c}')
|
import pickle
import base64
import os.path
import email
from io import BytesIO
from typing import List, Dict, Generator, Iterable, Optional, Union, Set
from googleapiclient.discovery import build, Resource
from google.oauth2.credentials import Credentials
from bs4 import BeautifulSoup
from tap_gmail_csv.gm... |
from .ref_pages import WPBasePage
class HomePage(WPBasePage):
def __init__(self, automator):
super().__init__(automator)
def login(self):
self.Browser().go_to_url(self.get_automator().get_config().get_user_option_value("wp.login.url").as_string())
self.Element("login").set_text("user... |
# -*- coding: utf-8 -*-
"""
******* 文档说明 ******
获取语料程序,以迭代器方式返回, 数据预处理模块
Time: 2020/11/26 21:46
Author: ChenXin
Version: V 0.1
File: bulletDensity.py
Describe: Github link: https://github.com/Chen-X666
"""
import logging
import os
from collections import Counter
from NewWordDiscovery.tool.langconv import ... |
from decimal import Decimal
from django.db.models.expressions import Exists, OuterRef, Subquery
from django.template import Context, Template
from django.test import TestCase, RequestFactory
from tests import factories
from beerfest.models import Beer, StarBeer, BeerRating
from beerfest.templatetags import beer_tags... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.