text stringlengths 957 885k |
|---|
import sys
import scipy.ndimage
import os.path
import HebbLearn as hl
import numpy as np
import matplotlib.pyplot as plt
try:
import h5py
except:
print('h5py cannot be loaded - may cause error')
pass
fl = hl.NonlinearGHA()
num_textures = 688
if os.path.isfile('textures.npy'):
print('==> Load previousl... |
<reponame>aimanahmedmoin1997/DataCamp
'''
How often do we get no-hitters?
The number of games played between each no-hitter in the modern era (1901-2015) of Major League Baseball
is stored in the array nohitter_times.
If you assume that no-hitters are described as a Poisson process, then the time between no-hitters i... |
<filename>pysvc/unified/client.py
##############################################################################
# Copyright 2019 IBM Corp.
#
# 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
#
#... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
import importlib
import time
class WidgetBase(QtCore.QObject):
messageBoxSignal = QtCore.pyqtSignal(str)
def __init__(self, *args):
super().__init__(*args)
self.signalManager = None
self.listener = None
self.list... |
from collections import namedtuple
from math import sqrt
import random
try:
import Image
except ImportError:
from PIL import Image
from colormath.color_objects import LabColor, sRGBColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie1976
import pandas as pd
im... |
<filename>src/enums.py
from enum import auto, Enum
from typing import List
class Interval(Enum):
"""
This enum describes the interval name
and the number of half steps it contains
"""
MINOR_2ND = (1, 'm2', 'minor 2nd')
MAJOR_2ND = (2, 'M2', 'major 2nd')
MINOR_3RD = (3, 'm3', 'minor 3rd')
... |
from math import sin, cos, radians
import numpy as np
from matplotlib import pyplot as plt
from shapely.geometry import Point, Polygon
def easyplt(poly1, poly2,img): # it is for development of the code for annotation.
poly1 = np.array(poly1)
xs1, ys1 = poly1[:,0], poly1[:,1]
xs2, ys2 = poly2[:,0], poly2[:,... |
# game.py
#
# GameGenerator is free to use, modify, and redistribute for any purpose
# that is both educational and non-commercial, as long as this paragraph
# remains unmodified and in its entirety in a prominent place in all
# significant portions of the final code. No warranty, express or
# implied, is made regardin... |
<filename>tests/test_issues/test_linkml_issue_723.py<gh_stars>0
import unittest
from dataclasses import dataclass
from enum import Enum
import rdflib
from linkml_runtime import SchemaView
from linkml_runtime.dumpers import json_dumper, yaml_dumper, rdflib_dumper
from linkml_runtime.linkml_model import PermissibleValue... |
# @author = "avirambh"
# @email = "<EMAIL>"
import torch
import torch.nn as nn
def print_vcls(vcls, epoch):
for vcl in vcls:
print("Step {}: Name: {} Loss: {}".format(epoch,
vcl.name,
vcl.get_layer_loss())... |
<reponame>CodeWithSwastik/Tech-Struck
import datetime
import re
from urllib.parse import urlencode
from discord import Color, Embed, Member
from discord.ext import commands
from jose import jwt
from cachetools import TTLCache
from config.common import config
from config.oauth import github_oauth_config
from models im... |
# Copyright (c) 2011, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condition... |
<filename>python-obj-system.py
#!/usr/bin/env python3
from mdpyformat import *
import pprintex
header_md("""Python object primer for Python3 / meta classes""" )
header_md("""Introduction""", nesting = 2)
print_md("""
Python is good at creating the illusion of being a simple programming language. Sometimes this ill... |
<reponame>bds-ailab/logflow
# Copyright 2020 BULL SAS All rights reserved #
from collections import Counter
from torch.utils.data import Dataset
import word2vec # type: ignore
import h5py # type: ignore
from loguru import logger
import time
import pickle
import numpy as np # type: ignore
DTYPE = np.float32
from typin... |
<filename>Image Classifier Part-2/predict_helper.py<gh_stars>0
from PIL import Image
import numpy as np
import torch
from make_model import make_model
from torch import optim
from torchvision import transforms
import argparse
def get_input_args():
parser = argparse.ArgumentParser()
parser.add... |
import sys
import os
import time
import functools
import itertools
from collections import OrderedDict
import contextlib
import queue
import threading
import subprocess
import signal
import shutil
import termios
import fcntl
import bisect
import numpy
import scipy
import scipy.signal
import pyaudio
import wave
import a... |
<reponame>molguin92/ganglion-biosensing
from __future__ import annotations
import logging
import threading
import time
from typing import Any, Callable, Iterator, List, Optional, Tuple
import numpy as np
from bitstring import BitArray
from bluepy.btle import DefaultDelegate, Peripheral
from ganglion_biosensing.board... |
<reponame>dreipol/django-green-grove<filename>django_green_grove/management/commands/backup_project.py
import logging
import os
import subprocess
import boto
from django.conf import settings
from django.core.management import BaseCommand
from django.utils.timezone import now
from ...backends import BackupStorage
log... |
<filename>test/test_cloud_translation_framework.py<gh_stars>10-100
import sys
import os
import pytest
import json
import functools
from nmtwizard.cloud_translation_framework import CloudTranslationFramework
from nmtwizard import serving
def _generate_numbers_file(path, max_count=12):
with open(path, "w") as f:
... |
<reponame>sphincs/pyspx<gh_stars>1-10
import pytest
import os
import random
import importlib
import struct
paramsets = [
'shake256_128s',
'shake256_128f',
'shake256_192s',
'shake256_192f',
'shake256_256s',
'shake256_256f',
'sha256_128s',
'sha256_128f',
'sha256_192s',
'sha256_192... |
<filename>pilates/utils/geog.py
import geopandas as gpd
import pandas as pd
import logging
import requests
from shapely.geometry import Polygon
from tqdm import tqdm
import os
logger = logging.getLogger(__name__)
def get_taz_geoms(region, taz_id_col_in='taz1454', zone_id_col_out='zone_id'):
if region == 'sfbay':... |
import logging
import h5py
import numpy as np
from collections import defaultdict
from minibatcher import MiniBatcher
class IAM_MiniBatcher:
@staticmethod
def shingle_item_getter(f, key, shingle_dim=(120,120)):
'''
Retrieve a line from an iam hdf5 file and shingle into the line
NB: shi... |
# Generated by Django 2.2.3 on 2020-08-25 19:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import ghostwriter.rolodex.models
class Migration(migrations.Migration):
dependencies = [
('rolodex', '0005_auto_20191122_2304'),
]
operatio... |
# Copyright 2018 The TensorFlow 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 applica... |
#!/usr/bin/python3
import unittest
from freeverse import Should, Expect, It
from freeverse.expectations import ActualValue
class ExpectationTests(unittest.TestCase):
def assertIsNotEmpty(self, sizedObject):
self.assertGreater(len(sizedObject), 0)
# Test the actual message here
class ShouldSt... |
import sys, getopt, inspect
def parseOptions(arguments, shortOpts, longOpts):
try:
options, remainder = getopt.getopt(
arguments,
shortOpts,
longOpts
)
command = None
try:
command = remainder[0]
remainder = remainder[1:]
... |
<reponame>olafura/hwidgets<gh_stars>1-10
import gobject
from dbus.mainloop.glib import DBusGMainLoop
import dbus
import json
DBusGMainLoop(set_as_default=True)
import NetworkManager
from mapping import wifi_states
from PySide.QtCore import QObject, Slot, Signal
#A simple class simulate simulate the access point inform... |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
"""FCN config system.
This file specifies default config options for Fast R-CNN. You should not
change values in this file. Instead, you s... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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... |
#! /usr/bin/env python3
# main.py - Get contents of text files and output the most frequent "interesting" words to an HTML file
# Author - <NAME>
# Date - November 2020
from page import head, middle, tail
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import sent_tokenize, word_tokenize
from ... |
from contextlib import suppress
import logging
import os
from threading import Thread, current_thread
from tempfile import NamedTemporaryFile
from uuid import uuid4
import requests
import prometheus_metrics
import custom_parser
import target_worker
logger = logging.getLogger()
CHUNK = 10240
MAX_RETRIES = 3
def _re... |
#!/usr/bin/env python
# Copyright (C) 2017 Udacity Inc.
#
# This file is part of Robotic Arm: Pick and Place project for Udacity
# Robotics nano-degree program
#
# All Rights Reserved.
# Author: <NAME>
# Import modules
import rospy
import pcl
import numpy as np
import math
import ctypes
import struct
import sensor_m... |
<gh_stars>10-100
from api.Repositories.TrackRepository import TrackRepository
from api.Services.AudioFeatureAttacherService import AudioFeatureAttacherService
from api.Services.GenreLabelAttacherService import GenreLabelAttacherService
from api.Spotify.SpotifyAPI import SpotifyAPIAccess
from sklearn.metrics.pairwise im... |
# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
import time
import json
import requests
from datetime import datetime
from dataiku.customrecipe import *
import dataiku_esri_content_utils
import dataiku_esri_utils
from dataiku_esri_utils import recipe_config_get_str_or_none
import common, enrichm... |
<reponame>mukundv-chrome/clusterfuzz
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
<filename>models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/caffe/cf_retinaface_wider_360_640_1.11G_1.3/code/test/visualTest/test.py
# -- Copyright 2019 Xilinx 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 obtai... |
<filename>app/blueprints/dynamic/generators/apo.py
import os, errno
from datetime import datetime
from ....config import Config
from shutil import which
def generate(
selecao_arquivo, campo_forca, modelo_agua, tipo_caixa, distancia_caixa,
neutralizar_sistema, double, ignore, current_user
):
if which("grace... |
import torch
import numpy as np
import resampy
from .mel_features import log_mel_spectrogram
"""
The only difference of this code from the original repository is that
it ensures the outputs contain at least a single frame
"""
def _preprocess(data, sample_rate):
# Architectural constants.
NUM_FRAMES = 96 #... |
<filename>ctrlengine/ai/test.py
###############################
### TESTING USB ACCELERATOR ###
###############################
# import cv2
# from face_detection import face_detection
# import time
# engine = face_detection()
# cam = cv2.VideoCapture(2)
# while True:
# start = time.time()
# ret, frame = cam.read(... |
<reponame>yangboz/maro
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from flask import Blueprint, abort
from ...master_api_server.jwt_wrapper import check_jwt_validity
from ...master_api_server.objects import local_cluster_details, redis_controller
from ...utils.connection_tester import Co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# 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-... |
<gh_stars>0
from numpy import inf, nan
from sklearn.decomposition import LatentDirichletAllocation as Op
from lale.docstrings import set_docstrings
from lale.operators import make_operator
class LatentDirichletAllocationImpl:
def __init__(self, **hyperparams):
self._hyperparams = hyperparams
self... |
<gh_stars>1-10
import os
import io
import sys
from unittest import TestCase, main as unittest_main
from eventhandler import EventHandler
class TestEventHandler(TestCase):
def test_001_initialization_args(self):
# Test init on no args
eh = EventHandler()
self.assertEqual(eh.count_events, 0... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ORStools
A QGIS plugin
QGIS client to query openrouteservice
-------------------
begin : 2017-02-01
git sha ... |
import asyncio
import datetime
import logging
import sys
from typing import List, Optional
import jwt as jwtlib # name conflict with jwt query param in /ws
import sentry_sdk
import sqlalchemy.exc
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, WebSocket, status
from fastapi.middleware.cors impor... |
"""External function interface to NNPACK libraroes."""
from __future__ import absolute_import as _abs
from .. import api as _api
from .. import intrin as _intrin
from .._ffi.function import _init_api
def config(nthreads):
"""Configure the nnpack library.
Parameters
----------
nthreads : int
T... |
<reponame>KvyatkovskyAleksey/ScrapeWebdriver<gh_stars>0
import os
import re
from itertools import cycle
# import seleniumwire.webdriver
from selenium.webdriver.remote.command import Command
from selenium import webdriver
from bs4 import BeautifulSoup
from webdriver_manager.firefox import GeckoDriverManager
from .exten... |
# -*- coding: utf-8 -*-
"""Tools to build Columns HighCharts parameters."""
from .base import JSONView
class BaseColumnsHighChartsView(JSONView):
"""Base Class to generate Column HighCharts configuration.
Define at least title, yUnit, providers, get_labels() and
get_data() to get started.
"""
pro... |
class basegraph:
"""
Graph interface.
add_node(element)
remove_node(node_id)
add_arc(nodeA_id, nodeB_id, info)
remove_arc(nodeA_id, nodeB_id)
set_arc_status(nodeA_id, nodeB_id, status)
get_nodes()
get_arcs()
get_num_nodes()
get_num_arcs()
get_node_by_id(node_id)
... |
<reponame>povellesto/blobydouche<filename>Blob Rage App/main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.vector import Vector
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProp... |
<filename>modpybass/pybasswma.py
# Copyright(c) <NAME> 2009 <EMAIL>
# http://vosolok2008.narod.ru
# BSD license
__version__ = '0.2'
__versionTime__ = '2013-01-22'
__author__ = '<NAME> <<EMAIL>>'
__doc__ = '''
pybasswma.py - is ctypes python module for
BASSWMA - extension to the BASS audio library,
enabling the playba... |
<reponame>dsommerville-illumio/resilient-community-apps
# -*- coding: utf-8 -*-
"""Tests using pytest_resilient_circuits"""
import pytest
from mock import patch
from resilient_circuits.util import get_function_definition
from resilient_circuits import SubmitTestFunction, FunctionResult
from resilient_lib import Integr... |
import typer
from rich.console import Console
from rich.table import Table
from ..core.pricing import PricingHandler
app = typer.Typer()
_handler = PricingHandler()
_data = _handler.get_all_prices()["pricing"]
_currency = _data["currency"]
_vat = f"{float(_data['vat_rate']):6.4f}"
_console = Console()
@app.callback... |
<filename>backend/admin/decapod_admin/external_execution.py
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Mirantis 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... |
"""
253. Meeting Rooms II
Medium
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
Constraints:
... |
from typing import Iterable, DefaultDict, List
from collections import defaultdict
from flask import Blueprint, Response, abort
from .models import Entry, Tag, EntryTag, AboutPage
from .utils import Paginator, template_response
blueprint = Blueprint(
name='controllers',
import_name=__name__,
static_fold... |
<gh_stars>0
""" Official evaluation script for v1.1 of the SQuAD dataset. """
from __future__ import print_function
from collections import Counter
import nltk
import string
import re
import argparse
import json
import sys
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespac... |
<reponame>oyente/oyente<gh_stars>10-100
# return true if the two paths have different flows of money
# later on we may want to return more meaningful output: e.g. if the concurrency changes
# the amount of money or the recipient.
from z3 import *
from z3util import get_vars
import json
import mmap
import os
import csv
... |
import io
import asyncio
import hashlib
import itertools
from datetime import datetime
from itertools import product
from contextlib import asynccontextmanager, AsyncExitStack
from typing import (
AsyncIterator,
Dict,
List,
Tuple,
Any,
NamedTuple,
Union,
Optional,
Set,
)
from .excep... |
<reponame>whfh3900/Tacotron-2-korea-example
import os
import numpy as np
import tensorflow as tf
from datasets.audio import save_wavenet_wav, get_hop_size, melspectrogram
from infolog import log
from wavenet_vocoder.models import create_model
from wavenet_vocoder.train import create_shadow_saver, load_averaged_model
f... |
#! /usr/bin/env python
import lib_robotis_xm430 as xm430
import sys
import time
import rospy
import actionlib
import o2as_msgs.msg
class ToolsAction:
def __init__(self):
name = rospy.get_name()
serial_port = rospy.get_param(name + "/serial_port", "/dev/ttyUSB0")
rospy.loginfo("Starting up ... |
<filename>scripts/analysis/plot_embedding.py
#!/usr/bin/python
import h5py
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import json
import codecs
from music21 import *
data = dict()
for embed in [... |
import numpy as np
import scipy.optimize as spo
'''
Metropolis-adjusted Langevin algorithm or Langevin Monte Carlo (LMC)
'''
def sampler(logpostfunc, options):
'''
Parameters
----------
logpostfunc : function
A function call describing the log of the posterior distribution.
If no... |
import os
import pytest
from sqlalchemy import Column, Text
from alembic import command
from alembic.autogenerate import render_python_code, produce_migrations
from alembic.config import Config
from alembic.migration import MigrationContext
from alembic.operations import Operations, ops
from sqlalchemy_bigint_id.sche... |
# -*- coding: utf-8 -*-
"""A set of python modules that aid in plotting scientific data
Plotting depends on matplotlib and/or mayavi and file reading uses h5py
and to read hdf5 / xdmf files.
Note:
Modules in calculator and plot must be imported explicitly since
they have side effects on import.
Attributes:
... |
<gh_stars>0
#!/usr/bin/env python3
#/***************************************************************************//**
# @file i_udp.py
#
# @author Black-Blade
# @brief i_udp.py
# @date 13.01.2021
# @version 0.0.1 Doxygen style eingebaut und erstellen dieser File
# @see https://tools.ietf.org... |
# yellowbrick.features.projection
# Base class for all projection (decomposition) high dimensional data visualizers.
#
# Author: <NAME>
# Created: Wed Jul 17 08:59:33 2019 -0400
#
# Copyright (C) 2019, the scikit-yb developers
# For license information, see LICENSE.txt
#
# ID: projection.py [21eb9d2] 43993586+<EMAIL... |
# *****************************************************************************
# Copyright (c) 2019-2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions o... |
<reponame>hypothesis/h-matchers<filename>tests/unit/h_matchers/matcher/collection/containment_test.py<gh_stars>0
# pylint: disable=misplaced-comparison-constant
import pytest
from h_matchers import Any
from h_matchers.matcher.collection.containment import (
AnyIterableWithItems,
AnyIterableWithItemsInOrder,
... |
<filename>django_mako_plus/router/discover.py
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.template import TemplateDoesNotExist
from django.views.generic import View
from .decorators import view_function, CONVERTER_A... |
<gh_stars>10-100
# EDGE Estimator for Shannon Mutual Information
#
# Created by <NAME> (<EMAIL>)
# Current version: 4.3.1
# Requirements: numpy, cvxpy(v1.0.6),scipy, sklearn
#
# 10/1/2018
#
# Based on the paper: Scalable Mutual Information Estimation using Dependence Graphs
#
################
# The estimator is ... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ThreeDiCustomStats
A QGIS plugin
This plugin calculates statistics of 3Di results. The user chooses the variable, aggregation method and spatiotemperal filtering.
Generated by Plu... |
import abc
import marshal
import dictdiffer
import six
def format_diff(differ, diff):
"""
Formats the given differ and diff for mongo storage.
:param differ: the differ object
:param diff: the diff
:return: a dict for storage
"""
return {u'id': differ.differ_id, u'd': diff}
def extract... |
<filename>data_processing/eccv2020-sharp-workshop/sharp/utils.py
import copy
import numbers
import cv2
import numpy as np
try:
from scipy.spatial import cKDTree as KDTree
except ImportError:
from scipy.spatial import KDTree
from .trirender import UVTrianglesRenderer
def slice_by_plane(mesh, center, n):
... |
<gh_stars>1-10
import pygame
class MouseInput:
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
pressed = [0, 0, 0]
@staticmethod
def _update():
MouseInput.mouse_pos = pygame.mouse.get_pos()
MouseInput.mouse_buttons = pygame.mouse.get_pressed()
... |
# -*- coding: utf-8 -*-
# Author:Guzhongren
# created: 2017-04-28
import os
import sys
import arcpy
from PIL import Image
reload(sys)
sys.setdefaultencoding("utf-8")
# tif 4波段图像转换为3波段图像 --未用
def band4_2_band3_raster(band4_raster_path, temp_file_path):
raster_arr = arcpy.RasterToNumPyArray(
band4_raster_... |
<reponame>timofriedl/multicam-ihgg
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torchvision.utils import make_grid, save_image
"""
A bunch of helpful functions for VAE training and general tensor / array conversions.
Original author: <NAME>
Heavily modified by <NAME>
"... |
<reponame>ArneBinder/nlp-formats
import glob
from abc import ABC, abstractmethod
from dataclasses import dataclass
from os import path
import nlp
@dataclass
class BratConfig(nlp.BuilderConfig):
"""BuilderConfig for BRAT."""
ann_file_extension: str = 'ann'
txt_file_extension: str = 'txt'
class Abstract... |
<reponame>anuwrag/opentrons
"""
otupdate.buildroot.update_actions: what files to expect and what to do with them
This module has functions that actually accomplish the various tasks required
for an update: unzipping update files, hashing rootfs, checking signatures,
writing to root partitions
"""
import contextlib
im... |
<gh_stars>0
# Leviton Cloud Services API model Installation.
# Auto-generated by api_scraper.py.
#
# Copyright 2017 <NAME> <<EMAIL>>
#
# This code is released under the terms of the MIT license. See the LICENSE
# file for more details.
from ..base_model import BaseModel
class Installation(BaseModel):
def __init__... |
# ------------------------------------------------------------------------------------------------ #
# MIT License #
# #
# Copyright (c) 2... |
import pytest
from py2vega import py2vega, Variable
from py2vega.main import Py2VegaSyntaxError, Py2VegaNameError
from py2vega.functions.math import isNaN
whitelist = ['value', 'x', Variable('cell', ['value', 'x'])]
def test_nameconstant():
code = 'False'
assert py2vega(code, whitelist) == 'false'
code... |
<filename>HTMLtoXML.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################
# From HTML to XML - InDesign flavour #
#######################################
### Modules
import re
import sys
from bs4 import BeautifulSoup
import HTMLParser
### Functions
def clean_linebreaks(html_string... |
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2018 <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 rights
# to use, c... |
import random
from collections import Counter
from enum import Enum, unique
from os import PathLike
from typing import Union, List
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from app.features import N_MELS
MODEL_PATH = 'models/emotions.pt'
@unique
class Emotion(Enum):
... |
<filename>examples/simple/classification/classification_pipelines.py
from typing import Optional
from fedot.core.log import Log
from fedot.core.pipelines.node import PrimaryNode, SecondaryNode
from fedot.core.pipelines.pipeline import Pipeline
def cnn_composite_pipeline(composite_flag: bool = True) -> Pipeline:
... |
import os.path
import pkgutil
import re
import tokenize
import pytest
import streamlink.plugins
import tests.plugins
from streamlink.compat import is_py2
from streamlink.plugin.plugin import Matcher, Plugin
from streamlink.utils.module import load_module
from streamlink_cli.argparser import build_parser
plugins_pat... |
<filename>tests/test_saving_calculators.py
import json
import unittest
from tests.test_base import BaseTest
from tests.saving_constants import (
AHORROS_JSON_0,
AHORROS_JSON_1,
AHORROS_PARA_META_JSON_0,
AHORROS_PARA_META_JSON_1,
AHORROS_PARA_META_RESULT_0,
AHORROS_PARA_META_RESULT_1,
... |
import bpy
import bpy_extras
import bmesh
from bpy.props import StringProperty
from .reader import AsciiModelReader
import os
class ImportOperator(bpy.types.Operator, bpy_extras.io_utils.ImportHelper):
"""This appears in the tooltip of the operator and in the generated docs"""
bl_idname = 'io_scene_modl.modl... |
<gh_stars>100-1000
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def associate_domain(self, FleetArn: str, DomainName: ... |
<gh_stars>1-10
import numpy as np
import pandas as pd
# to make this stable across runs
np.random.seed(22)
from sklearn.cluster import OPTICS
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import RobustScaler
from sklearn.model_selection... |
<reponame>gockxml/thumbor
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
import json
from thumbor.engines import BaseEngine
clas... |
<gh_stars>1-10
import os
from pathlib import Path
from typing import List
from mugen import Filter, MusicVideo, MusicVideoGenerator
from mugen.exceptions import ParameterError
from mugen.mixins import Persistable
from mugen.utilities import system
from mugen.video.effects import FadeIn, FadeOut
from mugen.video.io.Vid... |
import numpy as np
from scipy.spatial.distance import cdist
def cmeans(data, c, h, error, maxiter, metric='euclidean', init=None, seed=None):
"""
Fuzzy c-means clustering algorithm [1].
Parameters
----------
data : 2d array, size (S, N)
Data to be clustered. N is the number of... |
from datetime import datetime
import discord
import math
import typing
from discord.ext import commands
from cogs.boards import MockPlayer
from cogs.utils.db_objects import SlimDummyBoardConfig
from cogs.utils.paginator import (
SeasonStatsPaginator, StatsAttacksPaginator, StatsDefensesPaginator, StatsGainsPagina... |
<reponame>ska-telescope/sdp-prototype
# -*- coding: utf-8 -*-
"""Tango SDPSubarray device module."""
# pylint: disable=invalid-name
# pylint: disable=too-many-lines
# pylint: disable=wrong-import-position
# pylint: disable=too-many-public-methods
# pylint: disable=fixme
import os
import sys
import time
import signal
i... |
<filename>tests/learner/test_object_recognizer.py
import pytest
from more_itertools import first, one
from adam.language_specific.chinese.chinese_phase_1_lexicon import (
GAILA_PHASE_1_CHINESE_LEXICON,
)
from adam.curriculum.curriculum_utils import CHOOSER_FACTORY, phase1_instances
from adam.language_specific.engli... |
"""
TODO:
-) understand no boundary condition
-) validate understanding with analytical solution
"""
import nanopores, dolfin, os
from nanopores.physics.simplepnps import SimpleNernstPlanckProblem
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import force_profiles
from collections import de... |
import asyncio
import io
import logging
import pandas as pd
import core.real_time as creatime
import helpers.hasyncio as hasynci
import helpers.hprint as hprint
import helpers.hsql as hsql
import helpers.hunit_test as hunitest
import market_data as mdata
import oms.broker_example as obroexam
import oms.oms_db as ooms... |
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse, HttpResponseRedirect
from .models import PATIENT, FRAX, LVA, APSPINE, DUALFEMUR, COMBINATION
from uploads.core.models impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.