text stringlengths 3.07k 12.6k |
|---|
# Copyright (c) 2020 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... |
"""
===============
=== Purpose ===
===============
Stores versioned ECDC ILI data from ECDC website.
=======================
=== Data Dictionary ===
=======================
`ecdc_ili` is where the ILI data from ECDC is stored.
+----------------+-------------+------+-----+---------+----------------+
| Field ... |
"""
Name: create_normal_images.py
Desc: Creates surface normals versions of standard RGB images by using the matterport models.
This reads in all the point#.json files and rendering the corresponding images with
surface normals.
Requires (to be run):
- generate_points.py
"""
import os
im... |
"""handles preprocessing and saving data based on navbar selctions"""
from dash_extensions.enrich import Input, Output, State, ServersideOutput, dcc
from processing_scripts import process
import numpy as np
import pandas as pd
import globals
def hone_box_select(selected_data, df):
'''hone data to lats and lons c... |
# coding=utf-8
import warnings
from pathlib import Path
from textwrap import dedent
from clldutils.clilib import command, ParserError
from tabulate import tabulate
CHECKMARK = '✅'
ERROR = '❌'
@command(name='list', usage="list the datasets")
def listdatasets(args):
def label_trees(errors):
out = ''
... |
import bisect
import collections
import itertools
try:
from collections.abc import Mapping, MutableMapping
except ImportError:
from collections import Mapping, MutableMapping
class FrozenDict(Mapping):
"""
Object represents pairs key-value, and works like dict, but cannot be
modified. Also is has... |
### Deep Q-learning on catching block game
import numpy as np
import random
from collections import deque
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter... |
# -*- coding: utf-8 -*-
import xdl
import xdl_runner
import tensorflow as tf
import os
from xdl.python.training.export import get_latest_ckpt_v2
from exp_io.data_criteo import CriteoUplift1
from helper.models import EUEN
@xdl.tf_wrapper()
def model(is_treat, embeddings, label, is_training=True):
input = tf.concat(... |
# File: cpynet.py
# Author: <NAME>
# Created: 5 July 2018
# Purpose:
# Builds a class which represents a CP-network preference representation.
import xml.etree.ElementTree as xmlTree
import random
from os import listdir, path, system
from os.path import isfile, join, splitext
from uuid import uuid4
# Precond:
# i... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... |
import uuid, time, enum, contextlib
from sqlalchemy import Column, Integer, Text, String, DateTime, Sequence, Date, Boolean, Float, ForeignKey, Enum, \
PickleType
from sqlalchemy.ext.declarative import declared_attr
from web import sql,StateManger
from zspt.utils import generate_random_id, generate_hash
Model=sql.M... |
#!/usr/bin/env python3
import logging
import numpy as np
import time
import torch
import cv2
from . import transform as transform
logger = logging.getLogger(__name__)
def compute_frames_distances(frames, frame_pairs, num_frames, dist_func):
"""
This function computes the distance between all pairs of fram... |
from keras.callbacks import LearningRateScheduler, Callback
from keras.models import Model, load_model
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.utils import Sequence
from keras import backend as K
from .utils import chargen_encode_cat
impo... |
import asyncio
import discord
from datetime import datetime
from emoji import emojize as emojiA
from ritutils import channelbind, rolebind
config = {}
def emoji(s):
return emojiA(s, use_aliases=True)
class SignupPost():
ATTEND = 0
BAIL = 1
MAYBE = 2
LATE = 3
def __init__(self, client, channel, text):
self.c... |
#! /usr/bin/env python
from __future__ import print_function
from builtins import super
from collections import defaultdict
import random
class InvalidMoveError(Exception):
"""Exception Raised when Game move is not Allowed
"""
def __init__(self, message):
self.message = message
super().__... |
# -*- coding: utf-8 -*-
# Copyright 2018-2020 the orix developers
#
# This file is part of orix.
#
# orix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... |
""" Test iterative solvers """
# Author: <NAME> <<EMAIL>>
#
# License: MIT License
import numpy as np
import optim
import pytest
d = 3
def get_data_0():
c = np.array([2, 1, 0.5])
A = np.array([[.5, .5, 0], [0, .5, .5]])
b = np.array([1.0, 1.0])
Aeq = np.ones((1, 3))
beq = np.array([1.0])
... |
"""
This example code illustrates how to define your own basis function for the
DCF model.
It implements a modified version of the built in normalised polynomial model
but the structure is the same for more elaborate models.
As always we need to import the data, define an order :math:`{N}`
and import the function fitt... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
import sys
def proc_fields(ref, alt, af, msi):
# Filter low AF MSI
if msi:
msi = float(msi)
change_len = abs(len(ref) - len(alt))
if change_len == 1 and msi > 1:
msi_fail = any([
msi <= 2 and af < 0.005,
msi <= 4 and af < 0.01,
... |
import os
import sys
import ctypes
import time
import select
import logging
import binascii
import json
import datetime
import collections
D = logging.debug
L = logging.info
W = logging.warning
E = logging.error
DEFAULT_TRIES = 3
READLINE_SELECT_TIMEOUT = 1
def EX(msg, *args, **kwargs):
kwargs['exc_info'] = True... |
import os
import re
import json
from os.path import expanduser
import zipfile
import datetime
import tensorflow as tf
import numpy as np
from deepdrive_dataset.dataset_util import *
from deepdrive_dataset.deepdrive_versions import DEEPDRIVE_LABELS
from deepdrive_dataset.tf_features import *
from PIL import Image
imp... |
# -*- coding: utf-8 -*-
# {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2020, Battelle Memorial Institute.
#
# 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://w... |
# 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 may not u... |
from functools import wraps
import os
import pytest
import flask
from flask import request
from flask_sqlalchemy import SQLAlchemy
from marshmallow_sqlalchemy import ModelSchema, field_for
from marshmallow import fields
from flask_restful import Api
from flask_login import UserMixin, login_required, current_user
from ... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 23:07:54 2017
@author: vrtjso
"""
import numpy as np
import pandas as pd
import random
from operator import le, eq
from sklearn.decomposition import PCA
from sklearn import model_selection, preprocessing
def RMSLE(y, yfit):
n = len(y)
s = 0
... |
# Copyright (c) 2020. <EMAIL>
#
# 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, publish, distr... |
##A loop that implements a method like the ones in main_file(Needs to be renamed) and testImageNeurons. Then takes those results and sends them to the motors.
# Actually sending them to the motors have not been fully implemented yet. But the file in KTH-Neuro-Computing-Systems/Multi-motor does this. So just connecting... |
"""Simple Strace-Style Log Entry Parser
The parser converts a string representing a strace-style log entry
into an object representing the log entry and syscall
Grammar
-------
The highest level expression is a single strace log entry
Each strace entry is composed of a NUMBER representing the PID followed
... |
import torch
from torch import nn as nn
from binlin.model.modules.attention import AttnBahd
from binlin.model.nn_utils import get_lstm_unit, get_gru_unit
from typing import Tuple
class DecoderLSTM(nn.Module):
def __init__(self,
input_size: int,
hidden_size: int,
... |
"""Contains code to generate the individual datasets for all the predicates.
"""
import copy
import random
import warnings
from collections import defaultdict
import numpy as np
# Import tqdm_notebook if in Jupyter notebook
try:
from IPython import get_ipython
if "IPKernelApp" not in get_ipython().config:
... |
'''
Control the UVBot from a bluetooth client
using pyBluez with python 3
<NAME>: <EMAIL>
'''
import bluetooth
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import math
import time
import struct
serverMACAddress = 'B8:27:EB:C4:D0:94'
port = 1
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)... |
import itertools
import os
import json
from api_resource_file_operations import write_to_file, api_resource_keys_file, parameterized_api_resources_file
def get_json_api_resource(resource_items):
# form json_api_resource from resource_items
return '{' + ','.join(resource_items) + '}'
def get_keys_item(key, val... |
import glob
from re import IGNORECASE
import numpy as np
import os
import cv2
import pickle
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
from lxml.etree import Element, SubElement, tostring
from os import listdir, getcwd
from os.path import join
IGNORE_SMALL_OBJ = True
SMALL_OBJECT_THRET... |
from collections import defaultdict
import pymysql
import os
import json
from copy import deepcopy
mysql_host = os.getenv("HOST","localhost")
mysql_port = int(os.getenv("PORT","3306"))
mysql_user = os.getenv("USER","root")
mysql_pass = os.getenv("PASS","")
mysql_db = os.getenv("DB","fever")
def clean(s):
if b"SUP... |
"""Code to help visualize images, videos, plots, etc."""
import os
import cv2
import numpy as np
import torch
from PIL import Image
from detectron2.data import MetadataCatalog
from matplotlib import pyplot as plt
from torchvision.transforms import ToPILImage
from ..common_util.misc import makedirs
from ..devil import... |
import math
import torch
from torch import nn
from torch.nn import functional as F
from collections import OrderedDict
def attention(q, k, v, scale):
scores = torch.bmm(q.permute(1, 0, 2), k.permute(1, 2, 0)) / scale
attn = torch.softmax(scores, 2)
return torch.bmm(attn, v.permute(1, 0, 2)).permute(1, 0... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import torch
import logging
import sys
import torch.nn.functional as F
def get_logger(log_file):
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# logging to file
fileh = logging.Fi... |
#!/usr/bin/env python
# encoding: utf-8
r"""
3D shock-bubble interaction problem.
A planar shock wave impacts a spherical region of low density.
This problem involves the 3D Euler equations:
.. math::
\rho_t + (\rho u)_x + (\rho v)_y + (\rho w)_z & = 0 \\
(\rho u)_t + (\rho u^2 + p)_x + (\rho uv)_y & = 0 \\
... |
"""
NAME:
RVT local dominance esri raster function
rvt_py, rvt.vis.local_dominance
PROJECT MANAGER:
<NAME> (<EMAIL>)
Credits:
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
COPYRIGHT:
Research Centre of the Slovenian Academy of Sciences and Arts
U... |
from numpy import save as save_array
from os.path import join as path_join
from numpy import repeat
from avb.utils.visualisation import plot_latent_2d, plot_sampled_data, plot_reconstructed_data
from avb.model_trainer import AVBModelTrainer, VAEModelTrainer
from avb.utils.datasets import load_npoints, load_mnist
from a... |
import os
from .ansys_nodes_elements import write_request_node_displacements
from .ansys_nodes_elements import write_constraint_nodes
from .ansys_nodes_elements import write_nodes
from .ansys_nodes_elements import write_elements
from .ansys_materials import write_all_materials
from compas_fea.fea.ansys.writing.ansys_pr... |
"""
Core functions to evaluate piecewise polynomial interpolants (or their
derivatives) in one dimension. Additional functions are provided that do
this for two such interpolants, to facilitate the interpolation of paired
variables like salinity and temperature.
This subpackage is ideally suited when interpolation t... |
def savings(cls):
cls.account_type = 'savings'
return cls
def checking(cls):
cls.account_type = 'checking'
return cls
class Account:
pass
@savings
class Bank1Savings(Account):
pass
@savings
class Bank2Savings(Account):
pass
@checking
class Bank1Checking(Account):
pass
@checking... |
import logging
import os
import shutil
import jinja2
from unb_cli import project
logger = logging.getLogger(__name__)
TEMPLATES_PATH = os.path.join(project.UNB_CLI_D_PATH, 'templates')
CONFIG_FILENAME = '__config__.py'
def _template_path(name):
template_path = os.path.join(TEMPLATES_PATH, name)
if os.path.e... |
import argparse
import dowhy
from dowhy import CausalModel
import numpy as np
from pathlib import Path
import pandas as pd
import os, sys, time
import scipy
from tqdm import tqdm
from utils import timed_func, get_venue_names
def build_gml_string(features_df, target, treatment):
node_str = ""
edge_str = ""
... |
from enum import Enum, auto
from typing import Callable, Union
from petsc4py import PETSc
from mpi4py import MPI
img_exts = {'.bmp', '.dib', '.jpe', '.jpg', '.jpeg', '.jp2', '.png', '.pbm', '.pgm', '.ppm', '.sr', '.ras',
'.tif', '.tiff'}
vol_img_exts = {'.vti', '.vtk'}
class DataType(Enum):
NONE = a... |
# vim: filetype=python
# Copyright 2019 Autodesk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
"""
Audio-Image Networks
"""
from typing import Any, Tuple, Union
import torch
from torch import nn
from torchvision import models
from vit_pytorch import ViT
from wav2rec.data import transforms
from wav2rec.signal.dsp import MelSpectrogram
class AudioImageNetwork(torch.nn.Module):
"""Class of networks wh... |
#!/usr/bin/python
import os
from time import sleep
pubServer = "ssh <EMAIL>"
subServer = "ssh <EMAIL>"
nsqdServer = "ssh <EMAIL>"
lookupdServer = "ssh <EMAIL>"
directory = "/home/RTM/run-test/"
nsqdStart = "sh daemon_create.sh"
lookupdStart = "sh lookupd_create.sh"
def restartService():
os.system(" ".join([subServ... |
#!/usr/bin/env python3.7
import sys, getopt, json, socket
from http.server import BaseHTTPRequestHandler, HTTPServer
from shapely.geometry import Point, Polygon
from urllib.parse import urlparse,parse_qs
from urllib.request import urlopen
class StateEndpointHTTPRequestHandler(BaseHTTPRequestHandler):
states=... |
from sympy import fwht, ifwht
from itertools import product
'''
http://man.hubwiz.com/docset/SymPy.docset/Contents/Resources/Documents/_modules/sympy/discrete/transforms.html
The Walsh spectrum of a Boolean function is the product of its binary string (as a row vector) with a Walsh matrix.
https://en.wikiversity.org/... |
import os
import r
from discord.ext import commands
import discord
import random
class scythe(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.namebea = 0
self.givepoint = 0
@commands.command(name="コンパス")
async def compass_character(self, ctx, op=None):
"""(アタッカ... |
"""
Helpers to modify the flow of data through a :term:`chain`
"""
from __future__ import absolute_import, division
import itertools
import collections
import numbers
from .primitives.link import ChainLink
from .primitives.neutral import NeutralLink
from .signals import StopTraversal
from . import utility
__all__ = [... |
# Copyright 2021-2022 NVIDIA 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 ... |
import os
import pickle
import numpy as np
import xml.etree.ElementTree as ET
def parse_rec(filename):
'''
parse a xml file
:param filename: xml filename
:return: a list
'''
tree = ET.parse(filename)
objects = []
for obj in tree.findall('object'):
obj_struct = {}
obj_st... |
"""
Kivimäki: Developments in the theory of randomized shortest paths with a article_comparison of graph node distances
https://arxiv.org/abs/1212.1666
"""
import logging
import unittest
from sklearn.metrics import normalized_mutual_info_score
import numpy as np
from pygkernels import util
from pygkernels.cluster im... |
from __future__ import print_function
import errno
import json
import jwt
import os
import time
import uuid
import requests
from prominence import exceptions
def create_config_dir():
"""
Create the ~/.prominence directory
"""
try:
if not os.path.exists(os.path.expanduser('~/.prominence')):
... |
#!/usr/bin/env python3
import asyncio
import ssl
import exchangelib as ex
from email.message import EmailMessage
from email.utils import formataddr, formatdate
from email import policy
from hashlib import sha256 as _hash
import logging
def assurelist(obj):
'''Shortcut wrapper for handling the sometimes None `*_rec... |
class HashTableEntry:
"""
Linked List hash table key/value pair
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
# Hash table can't have fewer than this many slots
MIN_CAPACITY = 8
class HashTable:
"""
A hash table that with `cap... |
from typing import Union
from warnings import warn
from IPython.display import display
from kts.api.helper import Helper
from kts.core.backend.run_manager import run_manager, run_cache
from kts.core.feature_constructor.base import BaseFeatureConstructor
from kts.core.feature_constructor.generic import GenericFeatureC... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import time
import scipy
class BoundBox(object):
def __init__(self, xmin, ymin, xmax, ymax, c=None, classes=None):
self.xmin = xmin
self.ymin = ymin
self.xmax = x... |
# 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 may not use ... |
import streamlit as st
import pandas as pd
import github_command as gitcmd
import matplotlib.pyplot as plt
from ENV import dico_mapping
@st.cache
def load_metadata():
""" I know the code could be enhanced, but it is for the sake of clarity """
## urls
url_vehicules2017 = "https://static.data.gouv.fr/resources/bas... |
# -*- coding: utf-8 -*-
"""
ENPM661 Project 5, Spring 2020
<NAME>
Use this file to read in the exposure values for Scenario 2
and plot them on a heat map
"""
import ast
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from mat... |
import json
import logging
import requests
from django.utils import timezone
from celery_config import app
from django.apps import apps
from django.conf import settings
from apps.chahub.utils import ChahubException
logger = logging.getLogger(__name__)
def _send(endpoint, data):
url = f"{settings.CHAHUB_API_URL... |
#!/usr/bin/env python
"""
Optimal design of experiment modules
"""
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2021, USC"
#@title Imports and defaults
"""Kveton optimal design code"""
import numpy as np
from numpy.linalg import norm, inv, eigh, det, svd
from numpy.random import multinomial
... |
#
# This module contains helper functions for handling long DNS names, including compression.
#
from struct import pack
N = 0x40 # maximum valid length in a domain name + 1; N must be a power of 2.
def p8(x):
return pack("B", x)
def index_to_compression(idx):
assert idx <= 0x3fff
return pack... |
"""Utils tests"""
import datetime
from math import ceil
from tempfile import NamedTemporaryFile
from django.contrib.auth import get_user_model
import pytest
import pytz
from channels.models import SpamCheckResult
from open_discussions.factories import UserFactory
from open_discussions.utils import (
now_in_utc,
... |
# Created by lan at 2021/2/2
import dataclasses
import gzip
import itertools
import json
from dataclasses import dataclass, field
from enum import Enum
from functools import total_ordering
from typing import Tuple, List
@total_ordering
class CellIndex:
def __init__(self, row_index, column_index) -> None:
... |
import errno
import os
import signal
from functools import wraps
import numpy as np
from skimage.transform import resize
class TimeoutError(Exception):
pass
def timeout(seconds=5, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise Tim... |
"""Author: <NAME> (<EMAIL>)"""
import os
import dnnlib
import numpy as np
import PIL.Image
import torch
import legacy
import argparse
from torchvision import transforms
from fc_layer import FC_Model
import vggface2.senet as SENet
from datasets.vggface2_sg2 import StyleGAN2_Data as SDV
from datasets.sg2 import StyleGAN... |
import csv
import logging
import requests
import spf
import datetime
import json
from DNS import dnslookup
from DNS import DNSError
import DNS
from trustymail.domain import Domain
CSV_HEADERS = [
"Domain", "Base Domain", "Live",
"Sends Mail", "Mail Servers",
"SPF Record", "Valid SPF", "SPF Results",
... |
import pytest
from hypothesis import given
import astropy.units as u
from astropy.time import TimeDelta
import sunpy.net.dataretriever.sources.lyra as lyra
from sunpy.net import Fido
from sunpy.net import attrs as a
from sunpy.net._attrs import Instrument, Time
from sunpy.net.dataretriever.client import QueryResponse... |
"""
--- Day 21: Dirac Dice ---
There's not much to do as you slowly descend to the bottom of the ocean. The
submarine computer challenges you to a nice game of Dirac Dice.
This game consists of a single die, two pawns, and a game board with a
circular track containing ten spaces marked 1 through 10 clockwise. Each
pl... |
# -*- coding: utf-8 -*-
from pygaussmarkov.ParametricFreeNetworkConstraintSolver import ParametricFreeNetworkConstraintSolver
import numpy as np
import pygaussmarkov.GaussMarkovUtilities as GMUtils
import numpy.linalg as la
from operator import add, sub
import math
class NetworkSolver(ParametricFreeNetworkConstraintSo... |
import sys, itertools
from pylibs.test import Test, Player, BwChange, DelayChange, TcpDump
from pylibs.generic import PlainObject
server_url = 'http://192.168.100.10:3000/static'
bigbuckbunny8_url = server_url + '/bbb8/play_size.m3u8' # rates: 350k 470k 630k 845k 1130k 1520k 2040k 2750k, duration (s): ~600
settings =... |
import gdspy
from spira import log as LOG
from spira.core.parameters.initializer import ParameterInitializer
from spira.core.parameters.descriptor import RestrictedParameter
from spira.core.parameters.restrictions import RestrictType
from spira.core.parameters.variables import StringParameter
from spira.core.transform... |
from copy import copy
from wysiwygtemplate.base import WrapedDict
from wysiwygtemplate.templatebase import ExcelTemplate, ExcelProcessor, ExcelTemplateContext, ExpressionEvaluator
class ExcelArchetectureCommand:
pass
class LoopArchetectureCommand(ExcelArchetectureCommand):
collectionVarName: str
loopVar... |
"""
Minidemo (usando pysud_make) para pysud.
Demuestra uso de carga de datos generados por pysud_make.py
"""
import pysud_gm as gameMgr
import pysud
import pysud_events as ev
# Fichero de datos de juego creado con pysud_make:
DATAFILE = 'game.data'
##################################################################
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Script to send a umb message to be plugged in a finally task"""
import argparse
import json
import os
import subprocess
import sys
import typing
import urllib.request
import datetime
import uuid
class UMBNotificationError(Exception):
"""Custom exception when we f... |
import datetime
import logging
import os
import re
import sys
from time import mktime, sleep
import feedparser
import youtube_dl
from .config import Config
from . import db
from .utils import Utils
from .mpdutil import mpd_update, make_playlists
c = Config().conf_vars()
db = db.Database()
ut = Utils()
CONFIGPATH = ... |
# YouTube: https://www.youtube.com/watch?v=TB1p93msBFQ&list=PLtbC5OfOR8apSTahYrGIeEcp3nAB2o_CM&index=7
# Book: https://runestone.academy/runestone/books/published/pythonds/Recursion/ExploringaMaze.html
import turtle
PART_OF_PATH = 'O'
TRIED = '.'
OBSTACLE = '+'
DEAD_END = '-'
class Maze:
def __init__(self, maze_... |
import torch.nn as nn
import torch.nn.functional as F
from torch.tensor import OrderedDict
from collagen.core import Module
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.wei... |
from opencmiss.zinc.element import Element, Elementbasis
from opencmiss.zinc.field import Field
from opencmiss.zinc.node import Node
from opencmiss.zinc.context import Context
from opencmiss.utils.zinc.field import findOrCreateFieldCoordinates, find_or_create_field_group, findOrCreateFieldGroup
from opencmiss.utils.zin... |
# -*- coding: utf-8 -*-
import socket
import sys
class PortScanner:
def __init__(self, ip, ports): # Define objects properties
"""This of course defines the properties of the object."""
self.ip = ip
self.ports = ports
def valid_ip(ip): # Validate the ipv4 address given is valid
... |
# coding=utf-8
# Copyright (c) <NAME>
import argparse
import logging
import pathlib
import sys
import time
import SimpleITK as sitk
import xdrt
from xdrt import xdr_reader
from xdrt.utils import DATATYPES
def setup_logging(verbosity_level):
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
level = lev... |
import torch
from torchvision.models.resnet import ResNet
from torchvision.models.resnet import Bottleneck, conv1x1
from .layers import PeriodicConv2D
def circConv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, kernel_size=3, padding_mode='circular'):
"""3x3 convolution with padding"""
return Peri... |
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower
import cloudinary
# Outside models import
from .models import Images
from ... |
import os
from typing import List, Tuple
import argparse
from RanDepict import RandomDepictor
from multiprocessing.pool import MaybeEncodingError
def parse_arguments() -> argparse.Namespace:
"""
Parse arguments with argparse.
Returns:
Returns an namespace object that holds the given arguments
... |
from cm.model import CMObjectBase, CMStatusBase
from cm import datetime
class CaseManager(CMObjectBase):
def get(self, kw):
order_sql = self._get_sort_order(kw)
by = kw.get('sort_by')
if by == 'case_id':
by_sql = 'c.case_id'
elif by == 'description':
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 11:39:53 2021
@author: ayman
"""
import joblib
import torch
import argparse
import random
import numpy as np
from lib import game, mcts, model
def get_action(game, net, mcts_, cur_state,cur_player, search_depth, batch_size, device):
if net is None:
action... |
#!/usr/bin/env python3.6
"""
| Copyright (C) 2021 Institute of Computer and Network Engineering (IDA) at TU BS
| All rights reserved.
| See LICENSE file for copyright and license details.
:Authors:
- <NAME>
Description
-----------
pytest module: uses a test suite, defined in params of test_data to evaluate t... |
from enum import Enum
import time
import appdaemon.plugins.hass.hassapi as hass
import utils
__VERSION__ = "0.3.3"
# Mapping
# Init the options of select_option
class State (Enum):
Home = "home"
JustArrived = "just_arrived"
Away = "away"
JustLeft = "just_left"
ExtendedAway = "extended_away"
... |
import lxml.etree as ET
from django.http import Http404, HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from django.views.decorators.cache import cache_page
# Create your views here.
from .omenview import (
all_chapters,
get_chapter,
get_omen,
o... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2022 Quandela
#
# 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, ... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import logging
import rules
from pydantic import BaseModel
from typing import Optional
from django.shortcuts import redirect, reverse
from django... |
from src import configs
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import GroupKFold
def get_dataloader(mode='train', fold_index=0):
if mode == 'train':
train_set = TReNDsDataset(mode='train', fold_index=fold_index)
... |
from pathlib import Path
import numpy as np
from fastai.data.block import DataBlock, CategoryBlock
from fastai.data.transforms import ItemGetter
from fastai.learner import Learner
from fastai.vision.data import ImageBlock
from fastai.vision.learner import cnn_learner
from fastai.vision.core import PILImage
import pa... |
try:
import os, sys
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import askokcancel, showinfo
from tkinter.filedialog import *
import webbrowser
except:
print("ERROR: Missing fundamental packages (required: os, sys, tkinter, webbrowser).")
try:
sys.path.append(os.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.