text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*-
"""XML Validation.
XML Schema Definition (XSD):
https://www.w3.org/XML/Schema
Document Type Definition (DTD):
https://en.wikipedia.org/wiki/Document_type_definition
RELAX NG:
https://relaxng.org/
Validation with lxml:
https://lxml.de/validation.html
"""
from logging import... |
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import logging
from collections import OrderedDict
logger = logging.getLogger(__name__)
def export_param_card(benchmark, parameters, param_card_template_file, mg_process_directory, param_card_filename=None):
# Open par... |
import logging
import time
import requests
import lxml.etree
import lxml.html
import re
import decimal
from datetime import datetime, timezone, timedelta
from schema import ScopedSession, SyncState, User, Post, Comment
import os
import os.path
import gzip
logging.basicConfig(
filename=os.getenv("LOG_FILE", "../lo... |
from IMLearn.learners.classifiers import Perceptron, LDA, GaussianNaiveBayes
import numpy as np
from typing import Tuple
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import plotly.express as px
pio.templates.default = "simple_white"
from math import atan2, pi
de... |
"""
<NAME>
Computer Science, 1 course, UCU
Lab 1.2
"""
import folium
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderUnavailable
from haversine import haversine
def read_raw_file(lati, longli, year):
"""
(float, float, int) -> None
Function takes user's coordinates ... |
import torch.nn as nn
from typing import Tuple, Optional, Union, cast
from .utils import remove_batchnorm, insert_after, insert_before
from .condseq import CondSeq
from torchelie.utils import kaiming, experimental
from .interpolate import InterpolateBilinear2d
def Conv2d(in_ch, out_ch, ks, stride=1, bias=True) -> nn.... |
"""
:py:mod:`leapp.libraries.stdlib`
represents a location for functions that otherwise would be defined multiple times across leapp actors
and at the same time, they are really useful for other actors.
"""
import logging
import os
import sys
import uuid
import base64
from leapp.exceptions import LeappError
from leapp... |
#
#
# Public Archive of Days Since Timers
# Miscellaneous Helper Classes and Functions
#
#
#
# Imports
#
from pytz import all_timezones
# Standard Library Imports
import random
#
# Classes
#
class NonMetricMeasureInt:
"""The NonMetricMeasureInt class is intended to provide an easy way
to manage non-metric currenc... |
import numpy as _np
# TODO: Documentation!
def Get_CLVD_DC(Full_Moment):
M = Full_Moment
# isotropic part
M_iso = _np.diag(
_np.array([1.0 / 3 * _np.trace(M), 1.0 / 3 * _np.trace(M), 1.0 / 3 * _np.trace(M)])
)
M0_iso = abs(1.0 / 3 * _np.trace(M))
# deviatoric part
M_devi = M - M_... |
"""
Cisco Meraki Location Scanning Data simulator
Default port: 5002
<NAME>
2018
https://developer.cisco.com/site/Meraki
"""
# Libraries
from flask import Flask, request, render_template, redirect, url_for
import random
import datetime
import time
import requests
app = Flask(__name__)
# Globals
location_data = "... |
#!/usr/bin/python
from scipy import misc
from skimage import color
from skimage.measure import regionprops
import math
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import argparse
import sys
def toBinaryPxl(pixel):
if pixel != (0,0,0):
return (1,1,1)
else:
... |
import os
import sys
sys.path.append(os.path.abspath(os.path.pardir))
from argparse import ArgumentParser
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pytorch_lightning as pl
from torchmetrics.functional import iou
class DoubleConv(nn.Module):
"""(co... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import distutils.util
import os
import sys
import logging
from collections import defaultdict
# Use a non-interactive backend
import matplotlib
matplotlib.use('Agg')
import cv2
import tqdm
i... |
"""
Support for zeptrion_air_api.button_action_listener.
For more details about this Class, please refer to the documentation at
https://github.com/swissglider/zeptrionAirApi
"""
import time
import json
import asyncio
import websockets
class ButtonActionListenerHandler():
"""
This is the Button Action Liste... |
# Copyright (c) 2015 GigaSpaces Technologies Ltd. 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... |
# coding=utf-8
from OTLMOW.OTLModel.BaseClasses.AttributeInfo import AttributeInfo
from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut
from OTLMOW.OTLModel.Datatypes.DtcAfmetingBxhInMm import DtcAfmetingBxhInMm
from OTLMOW.OTLModel.Datatypes.DtcAfmetingDiameterInMm import DtcAfmetingDiameterInMm
from OTLM... |
import errno
import os
import time
from collections import OrderedDict
from vsqs.fswatcher import FSWatcher
micros = lambda: int(time.time() * 1000000)
MAX_CACHE_SIZE = 256
class QueueException(Exception):
"""Base exception for all queue related issues."""
class QueueFullException(QueueException):
"""Raise... |
import os
from collections import namedtuple
import mimetypes
import re
from lxml import html
from lxml.html.clean import Cleaner
from .common_utils import (is_valid_url, get_unique_filename_from_url, get_user_home_dir,
make_dir, dir_filename)
from .external.parse import search as parse_sear... |
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import itertools
# set font
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Helvetica'
# set the style of the axes and the text color
plt.rcParams['axes.edgecolor']='#333F4B'
plt.rcParams['axes.linewidth']=... |
"""Code for generating maximal couplings."""
import numpy as np
__all__ = [
"maximal_coupling_reference",
"maximal_coupling",
"ReflectionMaximalCoupling",
"reflection_maximal_coupling",
]
def maximal_coupling_reference(rv1, rv2):
"""Sample from a maximal coupling between distributions rv1 and rv2... |
""" Area pattern analysis tests.
Author:
<NAME>
Date:
Apr 2018
References:
"Introduction to Statistical Problem Solving in Geography",
<NAME>, Jr., <NAME>, Jr., <NAME>
"""
import numpy as np
class JointCountBinary(object):
""" Determine whether a random process has generated a binary (t... |
"""
A set of helper functions that have no other home.
"""
from math import degrees, radians, pi, sqrt, cos, sin
import numpy
def centerOfMass(positions, weights):
"""
Calculate the center of mass of a set of weighted positions.
Args:
positions: A list of (x,y,z) position tuples
weights: A list of pos... |
"""
Memoization classes
"""
import types
import functools as ftl
from pathlib import Path
import warnings
from .caches import Cache
# from .persistence import PersistantCache
from ..logging import LoggingMixin
# from ..interactive import exit_register
from collections import abc
from inspect import signature, _empt... |
# https://github.com/tejonaco/facepaster
from facenet_pytorch import MTCNN
from PIL import Image, UnidentifiedImageError
from io import BytesIO
import numpy as np
from math import asin, cos, degrees, radians
# OPTIONS
# overscaling face
X_SCALE_MARGIN = 1.1
Y_SCALE_MARGIN = 1.1
# start the face detector
mtcnn = MT... |
import csv
import warnings
import zipfile
import os
'''
****** AICUP spring 2021 check format ******
'''
'''
File extract
We check two things:
1. Upload file must be a .zip file
2. Contents need to contain two things : A. decision.csv B. qa.csv
'''
def file_extract():
# Get the uploaded compressed... |
import numpy as np
import trimesh
import torch
from torch_geometric.data import Data
# Expands triangles in object space
def expand_trig_np(verts):
pt1 = verts[:, 0, :]
pt2 = verts[:, 1, :]
pt3 = verts[:, 2, :]
line1 = pt1 - pt2
line2 = pt2 - pt3
line3 = pt3 - pt1
line1_len = np.linalg.nor... |
import argparse
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import Model as Net
import numpy as np
from utils import *
import random
import... |
import struct
from transmitter.BitField import BitField
import logging
logger = logging.getLogger(__name__)
class Message(object):
"""A Message is a packet of data which can be sent over the network.
Every Message has a unique msgID and usually some fields of data of a special type and a default value.
Cu... |
"""
Copyright 2017 <NAME>
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... |
from enum import Enum
from btypes import HorizontalAlignmentType, VerticalAlignmentType, ReadingOrderType, XFProperty, ColorType, \
PaletteColor, ThemeColor, SubscriptType, UnderlineType, FontFamilyType, CharacterSetType, FontSchemeType, FillType, GradientType, \
BorderType
from part.styles import Co... |
"""
Antelope Interface Definitions
The abstract classes in this sub-package define what information is made available via a stateless query to an Antelope
resource of some kind. The interfaces must be instantiated in order to be used. In the core package
"""
from .interfaces.abstract_query import PrivateArchive, En... |
#!/usr/bin/python
import sys
import os
import nltk
from nltk import sent_tokenize
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.tokenize import TreebankWordTokenizer,ToktokTokenizer
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from nltk.stem.snowball im... |
from keras.models import model_from_json
import pickle
from sklearn import preprocessing
def save_model(model, name, path =r'C:/Users/fkarl/PycharmProjects/NER/Model/NN_Models/connl03/'):
model_json = model.to_json()
with open(path+name+".json", "w") as json_file:
json_file.write(model_json)
# ser... |
import random
import sympy as sp
class Particle:
def __init__(
self,
func,
x0: list,
aCognitive: float = 2,
aSocial: float = 2,
inertia: float = 0.1,
dataset=None,
):
# DEBUG
self.coordinatesX = []
self.coordinatesY = []
s... |
#!/usr/bin/env python
"""
Script calling function primarybeammap_tant.py to calculate antenna temperature according to MWA beam model (analytic, AEE or FEE) and scaled Haslam map
Example usage:
python ./primarybeammap_tant_test.py -c 169 -p all -g 0 -m analytic
python ./primarybeammap_test.py -b 18,13,8,3,17,... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import csv, os
from scipy.stats.kde import gaussian_kde
class protein_length(object):
'''
Probability distributions of protein lenght across different organisms.
Protein length is calculated in amino acids (AA), based on the
... |
#
# Created on Mon Jun 14 2021
#
# The MIT License (MIT)
# Copyright (c) 2021 <NAME>
#
# 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 ri... |
import pandas as pd
from data.sql.sql_syntax import SqlSyntax
import data.labels as lb
import numpy as np
from data.config_reader import config_reader
from typing import List, Dict, Tuple
def get_min_avg_prices(data_start,
data_stop,
sql,
market):
rows = sql.select_min_... |
import os
import sys
class _Utilities:
@staticmethod
def _unify_ini(string):
string = string.replace("\n", "")
if string.startswith("#"):
return "#" + string.lstrip("#").lstrip().rstrip()
elif "=" in string:
return "=".join([a.lstrip().rstrip() for a in string.split("=")])
else:
return string
@s... |
"""Transform raw dataset into model's features."""
import os
import pandas as pd
from src.features.categories import categ
def load_data(data_path):
"""Return dict with filenames as keys and file content as values."""
data = dict()
for dirname, _, filenames in os.walk(data_path):
for filename in ... |
from nixui.utils import cache
from nixui.options import parser, nix_eval
import base64
import json
import os
import requests
import tempfile
import re
from github import Github, UnknownObjectException
@cache.cache()
def get_repos_blob_urls(access_token, repo_name):
g = Github(access_token)
user, repo = repo... |
# Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
'''Testing module for `python_toolbox.nifty_collections.LazyTuple`.'''
from __future__ import generator_stop
import uuid
import itertools
import collections
from python_toolbox import cute_iter_tools
from python_toolbox import sequen... |
'''https://medium.com/google-cloud/optimizing-tensorflow-models-for-serving-959080e9ddbf
'''
import tensorflow as tf
from keras import backend as K
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.python import ops
import os
def get_size(model_dir, model_file='saved_model.pb'):
'''Get ... |
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, redirect, reverse
from django.utils.decorators import method_decora... |
import os
import sys
import re
from datetime import datetime, timedelta
import time
import math
import requests
from io import StringIO
import numpy as np
import pandas as pd
import cvxopt
import cvxopt.blas
import cvxopt.solvers
from statistics import variance
## Loading historical prices ###########################... |
from heartcontour.data_wrangling.lvhyp_reader import Patient, EndPhase
from heartcontour.utils import progress_bar
from heartcontour.utils import get_logger
from standard import ViewPlane
from collections import defaultdict
import pickle
import os
logger = get_logger(__name__)
class Sample:
def __init__(self, p... |
import os
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
def get_mse(file_name: str, best_k: int, num_sample: int, num_most_k: int) -> float:
assert best_k <= 15
offset_start = 4
diff_col_num = 5
offset_between_sample = 2
mse_list = []
df = pd.read_... |
#
# Dump the header for a ZCode file
#
import sys
import argparse
from zmachine.interpreter import Interpreter,Story,StoryFileException
from zmachine.text import ZTextException
from zmachine.memory import Memory
from zmachine.instructions import InstructionException
class DumpScreen(object):
def __init__(self):
... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import dataset
import tensorflow.contrib.layers as layers
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim import arg_scope
# def playground_loss_function(labels, logits):
# # in rank 2, [elements, classes]
#
# # tf.... |
# For the links to the edited Wikidata pages, please visit:
# https://www.wikidata.org/wiki/User:Nizz009/ATP_edit_links
# For some pictures of the output (generated in CLI) while executing the script, please visit:
# https://drive.google.com/drive/folders/1HV7CyyMT09eaUcbyb6JkO4qbbyk9VQwL?usp=sharing
import pywikibot... |
# floyd_warshall.py
"""
The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can
have negative edge weights.
"""
def _print_dist(dist, v):
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
for i in range(v):
for j in ra... |
"""
No. Not every individual or group practice in PECOS is included on Physician
Compare. In order to be included on the site, individual health care
professionals must also:
- Have at least one practice location address in PECOS
- Have at least one specialty in PECOS
- Have submitted a Medicare claim within the last ... |
# Run OCR on images and identify business blocks using a combination of tesseract, opencv
from numpy.core import multiarray
from BusinessBlockFinder import BusinessBlockFinder
from Repository import Repository
from Annotation import Annotation
from Coordinate import Coordinate
from DataSource import DataSource
from Tex... |
import importlib
import tensorflow as tf
import numpy as np
import os
import tensorflow.contrib.layers as layers
def rendering_Net(inputs, masks, height, width, n_layers=12, n_pools=2, is_training=True, depth_base=64):
conv_layers = np.int32(n_layers/2) -1
deconv_layers = np.int32(n_layers/2)
# number of layers be... |
import json
from pathlib import Path
from collections import defaultdict
import argparse
from metric_test import Metric
from normalize import normalize
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
def flatten(li):
return [item fo... |
#!/usr/bin/python
# Wflow is Free software, see below:
#
# Copyright (c) <NAME> 2005-2011
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
from rdp import rdp
from utils import hull
FINGER_NAMES = ["Thumb", "Index", "Middle", "Ring", "Pinky(Little)"]
BONE_NAMES = ["PIP", "DIP", "TIP"]
def count_num_in_convex_hull(points_, convex_hull_):
'''
:param points_: points in... |
import datetime
import hmac
import logging
import os
from base64 import b64encode
from urllib.parse import quote, urljoin
import aiofiles
import aiohttp
from aiohttp import web
from cachetools import TTLCache
from decouple import config
from util import CACHE_MAX_AGES, filter_headers
__version__ = '2.0.0'
#
# con... |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from simplemooc.courses.models import Course, Enrollment, Lesson, Material
from simplemooc.courses.forms import ContactCourse, CommentForm
from simplemooc... |
"""
Usage:
from matplotlib import pyplot as plt
from random import randint
from itemnetwork import LinkedNetwork
from itemnetwork import quick_plot
# network setup
my_network = LinkedNetwork(ignore_key_equality_error=True)
# ignore_key_equality_error=True ignores an item if a == b (you can't connect self to self in a ... |
#!/usr/bin/env python
# <<<<<<< HEAD
###########################################################################
# Use STARE partitions to construct something resembling the original granule.
###########################################################################
import os, fnmatch
import matplotlib as mpl
impo... |
__author__ = 'thor'
from sklearn.feature_extraction import DictVectorizer
from sklearn.externals import six
import numpy as np
from pandas import DataFrame
from collections import Counter
class IterDictVectorizer(DictVectorizer):
"""Transforms lists of feature-value mappings or rows of a dataframe to vectors... |
import src.Planning.ProbabilisticRoadmap.RandomConfigSampler as rcs
import src.Planning.ProbabilisticRoadmap.RoadmapNode as rn
import kdtree as kd
import heapq as pq
import numpy as np
def _kdtree_distance(node, point):
return _distance(node.get_config(), point)
def _distance(config_start, config_end):
left_x... |
import click
from corgie import scheduling, helpers, stack
from corgie.log import logger as corgie_logger
from corgie.layers import get_layer_types, DEFAULT_LAYER_TYPE, str_to_layer_type
from corgie.boundingcube import get_bcube_from_coords
from corgie.argparsers import (
LAYER_HELP_STR,
create_layer_from_spe... |
from tensorflow.keras.layers import Bidirectional, concatenate, Input
from tensorflow.keras.layers import Dropout, Dense, LSTM, Embedding, GaussianNoise
from tensorflow.keras.layers import MaxPooling1D, Conv1D
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.r... |
"""
Created on September 04 16:54, 2020
@author: fassial
"""
import os
import warnings
import numpy as np
# loc params
PREFIX = ".."
DATASET_PATH = os.path.join(PREFIX, "dataset")
ENCODE_PATH = os.path.join(PREFIX, "encode")
MODEL_PATH = os.path.join(PREFIX, "model")
"""
load_data:
load data from file.
@para... |
from django.test import TestCase
from django.contrib.auth import get_user_model
# reverse is used to generate the API url
from django.urls import reverse
# rest framework test helper tools such as APIClient to make requests to the
# API and see what the response is.
from rest_framework.test import APIClient
# Let's use... |
"""
MIT License
Copyright (c) 2021 TheHamkerCat
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, di... |
# Copyright (c) 2021 <NAME>. All rights reserved.
# Licensed under the MIT License.
import tensorflow as tf
import numpy as np
import musdb
import random
import gc
from tqdm import tqdm
from typing import Union, List, Tuple, Dict
class DatasetParam:
"""Contains parameters for dataset generation.
Attributes:... |
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any, Final, Optional
from aioredis import Redis
from . import ScriptBase
from ..keys import CleanupKeys, NamespaceKeys, ContentKeys, MailboxKeys
__all__ = ['MailboxScripts']
class MailboxScripts:
def __init__... |
# Copyright 2020 KCL-BMEIS - King's College London
# 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... |
from grid import Grid
from node import Node
def run(grid, start, goal):
start_node = Node(None, start)
goal_node = Node(None, goal)
open_nodes = []
closed_nodes = []
open_nodes.append(start_node)
while len(open_nodes) > 0:
node = open_nodes[0]
node_index = 0
for inde... |
##############################################################################
#
# Copyright (c) 2001, 2002 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.
# T... |
"""
Find size of objects in an image based on the size of reference object
"""
from scipy.spatial import distance as dist4
import numpy as np
import cv2
import argparse
from scipy.spatial import distance as dist
def midpoint(ptA, ptB):
return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
def order_points... |
import os
import pudb
import shutil
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from scipy.io import loadmat, savemat
def patientwise_splitting(train, test, img_list):
patient_ids = [f.split('_')[1] for f in img_list]
patient_ids = list(set(patient_ids))
train_ids, test_ids ... |
import enum
import re
import json
import lxml.html
import websockets
from requests import Response
from typing import Optional, Dict
from . import atconnect
from . import aterrors
from . import atfm
from . import atconf
from . import atplayers
from .atwss import AternosWss
JAVA = 0
BEDROCK = 1
clas... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import keras.backend as K
from keras.engine import InputSpec, Layer
from keras import initializers, regularizers, constraints
from ...hyp_defs import float_keras
from ..constraints import ... |
# -*- coding: utf-8 -*-
import json
import uuid
import re
from datetime import datetime, date
from time import mktime
from vilya.libs.text import trunc_utf8
from vilya.models.consts import DOUBAN_EMAIL
class CJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
... |
# 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... |
# http://turing.com.br/material/flask/index.html
# https://demos.creative-tim.com/material-dashboard-dark/docs/2.0/components/card.html
# https://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/Python3_Flask.html
# https://fonts.google.com/icons?selected=Material+Icons:add_circle_outline&icon.query=down
from cs... |
#!/usr/bin/env python
'''======================================================
Created by: <NAME>
Last updated: May 2015
File name: quadrants_traj.py
Organization: RISC Lab, Utah State University
Notes:
======================================================'''
#======================... |
"""Tests for runway.cfngin.hooks.command."""
from __future__ import annotations
# pylint: disable=no-self-use
# pyright: basic
import os
import unittest
from subprocess import PIPE
from typing import (
TYPE_CHECKING,
Any,
ContextManager,
List,
Optional,
Tuple,
Type,
Union,
)
import moc... |
import numpy #numpy is used to make some operrations with arrays more easily
import pandas as pd
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
__errors__= []; #global variable to store the errors/loss for visualisation
columns... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ <NAME> + <NAME>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxy... |
import numpy as np
import pandas as pd
def cosine_similarity(vec1, vec2, normalize=False):
ans = np.dot(vec1 / np.linalg.norm(vec1), vec2 / np.linalg.norm(vec2))
if normalize:
ans = 0.5 + 0.5 * ans
return ans
def item_cf():
userID = 1
itemID = 'E'
n = 2 # SELECT TOP-K Item Similarity
... |
"""
# Hdl21 Built-In Generators Library
"""
import copy
from dataclasses import asdict, replace
from typing import Optional, Tuple, Union
from . import primitives
from .primitives import MosType, MosVth
from .generator import generator
from .module import Module
from .params import paramclass, Param
from .signal im... |
# (C) Datadog, Inc. 2022-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import hashlib
import time
import traceback
from abc import ABC, abstractmethod
import pymqi
from datadog_checks.base.constants import ServiceCheck
from datadog_checks.base.utils.serialization import jso... |
## Copyright 2015 Knossos authors, see NOTICE file
##
## 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... |
'''
Family 3
buddy list management
'''
import struct, logging, oscar
from util.primitives.funcs import do
from datetime import datetime
unpack_int = lambda v: struct.unpack('!I', v)[0]
subcodes = {}
log = logging.getLogger('oscar.snac.x03')
x03_name="Buddy List management"
def x03_init(o, sock, cb)... |
import pygame
import pygame.locals
from random import randrange
white=(255,255,255)
black=(0,0,0)
green=(0,255,0)
red=(255,0,0)
blue=(0,0,255)
ciano=(0,191,255)
cinza=(232,232,232)
try:
pygame.init()
print('O modulo pygame foi inicializado com sucesso')
except:
print('O modulo pygame não foi inicializado... |
import statistics
import uuid
from django.db import models
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from django.core.mail import send_mail
from django.conf import settings
class Project(models.Model):
name = models.CharFi... |
from odoo import models, fields, api
from odoo.tools import config
from os import path
from yaml import load, SafeLoader
import re
import logging
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.DEBUG)
def get_workflow_file_abspath(filename):
addons_path = config['addons_path'].split(',')
for a... |
import os.path
import sys
import pytest
from shapely.geometry import LineString
from shapely.geometry import Point
import conftest
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from interpoint import models
class TestPtOnEdge:
def ... |
import os
import cv2
import multiprocessing
from moviepy.tools import subprocess_call
from moviepy.config import get_setting
from moviepy.editor import VideoFileClip, AudioFileClip
from moviepy.audio.AudioClip import concatenate_audioclips
class Video_meta():
def __init__(self,video_file_name):
self.file_n... |
"""Settings, Logging and Timing
Sets global variables like verbosity, manages logging and timing.
"""
# Note
# ----
# The very first version (tracking cpu time) of this was based on
# http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution
import time
from functools import reduce
# d... |
import streamlit as st
import numpy as np
import pandas as pd
import sqlite3
conn=sqlite3.connect('data.db')
c=conn.cursor()
import os
import warnings
warnings.filterwarnings('ignore')
import tensorflow.keras as tf
import joblib
import base64
from io import BytesIO
ratings_1=pd.read_csv("ratings_1.csv")
ratings_2=... |
import os
import random
from collections import namedtuple
from enum import Enum
from pprint import pprint
from typing import List
import pygame
from pygame import freetype
from pygame.constants import QUIT, KEYDOWN, K_ESCAPE, MOUSEBUTTONUP
from pygame.rect import Rect
SCREENRECT = Rect(0, 0, 1000, 1000)
PANE_WIDTH =... |
import typing
from packaging import version
from httpx import __version__, Timeout as HTTPXTimeout, Request, Response
try:
from httpx.config import (
UnsetType,
UNSET,
TimeoutTypes,
VerifyTypes,
CertTypes,
DEFAULT_TIMEOUT_CONFIG,
DEFAULT_MAX_REDIRECTS,
)... |
# This file is public domain, it can be freely copied without restrictions.
# SPDX-License-Identifier: CC0-1.0
'''Running this file directly from the command line generates the necessary
DCT coefficient hex file.'''
import numpy as np
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import FallingEd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.