text stringlengths 2 999k |
|---|
import org.apache.hadoop.fs.permission.FsPermission
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
val loc = "/tmp/hwc/"+sc.sparkUser
def createTmpDir(): Unit={
val conf = new Configuration()
val fs= FileSystem.get(conf)
val Permission = new ... |
#!/usr/bin/env python3
import sqlite3
DB_NAME= "company.db"
EMPLOYEES=[(1, "Ivan Ivanov", 5000, 10000, "Software Developer"),
(2, "Rado Rado", 500, 0, "Technical Support Intern"),
(3, "Ivo Ivo", 10000, 100000, "CEO"),
(4, "Petar Petrov", 3000, 1000, "Marketing Manager"),
(5... |
import numpy as np
import theanets
import theano.tensor as TT
class TestLayer:
def test_build(self):
for f in 'feedforward Feedforward classifier rnn lstm'.split():
l = theanets.layers.build(f, nin=2, nout=4)
assert isinstance(l, theanets.layers.Layer)
class Base:
def setUp(s... |
""" Code for word tokenization: Arabic
"""
__author__ = ["TK", "Patrick J. Burns <patrick@diyclassics.org>"]
__license__ = "MIT License."
from cltk.phonology.arb.utils.pyarabic import araby
from cltk.tokenizers.word import WordTokenizer
class ArabicWordTokenizer(WordTokenizer):
"""
Class for word tokenizer ... |
"""
Tests for the entry point of pypy-c, app_main.py.
"""
from __future__ import with_statement
import py
import sys, os, re, runpy, subprocess
from rpython.tool.udir import udir
from contextlib import contextmanager
from pypy.conftest import pypydir
from lib_pypy._pypy_interact import irc_header
banner = sys.version.... |
#
# Copyright 2016 Quantopian, 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 or agreed to in wr... |
"""
Don't delete. Required for `package.module.function` import testing.
"""
def upper(item):
return item.upper()
|
#!/usr/local/python3.7
# -*- coding:utf8 -*-
#check_in
import requests
from configparser import ConfigParser
config = ConfigParser()
#print(len(config.read('config.ini'))==0)
if len(config.read('config.ini')) == 0:
print('配置文件为空,准备创建配置文件')
config.add_section('bbs1')
config.set('bbs1','cookie','null')
... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=li... |
import logging
from abc import ABC, abstractmethod
from managedtenants.core.tasks_loader.environment import Environment
from managedtenants.core.tasks_loader.exceptions import TaskFail, TaskSkip
class PostTask(ABC):
def __init__(self, addons, args, path):
self.addons = addons
self.environment = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
name = "screenkey"
source = "https://aur.archlinux.org/screenkey.git"
|
from fastapi import FastAPI, WebSocket
import uvicorn
import torch
import time
import json
from torch import optim
from torch.utils.data import DataLoader
import logging
from aux import train_one_epoch, get_lr
from threading import Thread
import copy
from utils.AverageMeter import AverageMeter
import itertools
import n... |
"""
WSGI config for linklab project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTI... |
class SubmissionFilter(object):
""" methods to determine whether a submission is relevant for reposting """
def __init__(self, settings):
""" store settings """
self.settings = settings
def _is_valid_submitter(self, submission):
""" returns True when the submission isn't from an ig... |
"""
Script that analyzes MPG Ranch archive logs of commands that add clip
start indices.
"""
from collections import defaultdict
from pathlib import Path
import csv
import re
# 2016
# ARCHIVE_DIR_PATH = Path('/Volumes/2012_2015_2016/2016_NFC/2016_NFC_All')
# JOB_NUMS = (88, 100, 118, 122, 123, 125, 126)
# OUTPUT_FI... |
#!/usr/bin/python3
# Copyright 2020 Josh Bailey (josh@vandervecken.com)
## 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, cop... |
""" WorkQueueExecutor utilizes the Work Queue distributed framework developed by the
Cooperative Computing Lab (CCL) at Notre Dame to provide a fault-tolerant,
high-throughput system for delegating Parsl tasks to thousands of remote machines
"""
import threading
import multiprocessing
import logging
from concurrent.fu... |
# -*- coding: utf-8 -*-
# Copyright (c) 2005-2013 Stephen John Machin, Lingfo Pty Ltd
# This module is part of the xlrd package, which is released under a
# BSD-style licence.
from __future__ import print_function
from array import array
from struct import calcsize, unpack
from .biffh import *
from .formatting impor... |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from fontTools.misc.textTools import safeEval, num2binary, binary2num
from fontTools.ttLib.tables import DefaultTable
import logging
log = logging.getLogger(__name__)
# panose classif... |
import unittest
import pyalgo.math.euler
class TestEuler(unittest.TestCase):
def test_gcd(self):
result = pyalgo.math.euler.gcd(16, 72)
answer = 8
self.assertEqual(result, answer)
def test_lcm(self):
result = pyalgo.math.euler.lcm(16, 72)
answer = 144
self.asse... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RTidyr(RPackage):
"""An evolution of 'reshape2'. It's designed specifically for data tidyi... |
"""OAuth2 session client to handle authentication of calls to the Monzo API
Adapted from the implementation for a Fitbit API Python client by Orcas, Inc.
and used under the Apache2 license: https://www.apache.org/licenses/LICENSE-2.0
Original code may be found at: https://github.com/orcasgit/python-fitbit
"""
from ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 2017 jfrfonseca
#
# 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 ... |
import requests
import urllib.parse as urlparse
import os
from urllib.parse import parse_qs
from helpers import downloadVideo, makeDir, threadline
docid = input("Enter docid (or filename that has docids): ")
mode = 0 if not os.path.exists(docid) else 1
rootPath = "FromID"
makeDir(rootPath)
makeDir(f"{rootPath}\\Videos... |
"""Optimizes force field parameters to fit some ground truth data"""
from openff.bespokefit.optimizers.base import (
BaseOptimizer,
deregister_optimizer,
get_optimizer,
list_optimizers,
register_optimizer,
)
from openff.bespokefit.optimizers.forcebalance import ForceBalanceOptimizer
__all__ = [
... |
#!/usr/bin/env python
# encoding=utf-8
#codeby 道长且阻
#email @ydhcui/QQ664284092
import re
import socket
import os
import struct
import array
import time
from threading import Thread
from core.util import CoroutinePool,gethosts,getports
from core.log import logging
PORTS = "1,3-4,6-7,9,13,17,19-26,30,32-33,3... |
import logging
from sultan.core import Base
from sultan.echo.colorlog import StreamHandler, ColoredFormatter
from sultan.config import settings
handler = StreamHandler()
handler.setFormatter(ColoredFormatter(
settings.LOG_FORMAT,
log_colors=settings.LOG_COLORS
))
def getLogger(name='', level=logging.DEBUG):
... |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. 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... |
#!/usr/bin/env python
# coding: utf-8
import pickle
from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASYN
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import os
# Load Data
filepath = '/Users/tim/src/Metis/Project_3/data/interim/df_merge3.pkl'
wit... |
import time
from mysql.connector import connect, Error
import click
from colr import color
def update():
coluna = input(color(' Column? » ', fore='#f29b85'))
ident = input(color(' ID? » ', fore='#f29b85'))
print(color(' Write your update', fore='#f29b85'))
time.sleep(0.3)
update = click.edit()
... |
'''this module for the data was emported from excel sheet analysis'''
import pandas as pd
import openpyxl as xl
from openpyxl import load_workbook
import numpy as np
import os
from copy import copy
import random
from random import randint,seed
from openpyxl.chart import BarChart, Reference, Series,LineChart
from .col... |
# Generated by Django 2.1.15 on 2021-09-02 13:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_ingredient'),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', ... |
from __future__ import absolute_import, division, print_function
from bisect import bisect
from collections import Iterable, Mapping
from collections import Iterator
from functools import partial, wraps
from itertools import product
import math
from numbers import Number
import operator
from operator import add, getit... |
from src.DataReader.KF_Data.KF_PrepData import DataManager
from scipy import signal
from src.Params import *
from src.Models.KF_Model.KF_BLock import *
from src.Models.KF_Model.KF_Model import *
import torch.optim as optim
import matplotlib.pyplot as plt
from src.Params import getNoiseLevel
dsName, subType, seq = 'ki... |
#!/usr/bin/env python
# Copyright 2019 The Vitess Authors.
#
# 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 applicabl... |
# coding: utf-8
"""
Looker API 3.0 Reference
### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token.... |
import emission.storage.decorations.analysis_timeseries_queries as esda
import emission.analysis.modelling.tour_model.cluster_pipeline as pipeline
import emission.analysis.modelling.tour_model.similarity as similarity
import pandas as pd
from sklearn.model_selection import KFold
# read data that have user labels
def ... |
import os
from pepys_import.core.formats.rep_line import REPLine
from pepys_import.core.formats import unit_registry
from pepys_import.core.validators import constants
from pepys_import.file.importer import Importer
class ReplayImporter(Importer):
def __init__(
self,
name="Replay File Format Impo... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/services/age_range_view_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protob... |
import inspect
import math
import pprint
from collections.abc import Iterable
from collections.abc import Mapping
from collections.abc import Sized
from decimal import Decimal
from itertools import filterfalse
from numbers import Number
from types import TracebackType
from typing import Any
from typing import Callable
... |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class imageGreyDilate(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_mana... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/protobuf/config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import distutils.util
import os
import sys
import pprint
import subprocess
from collections import defaultdict
from six.moves import xrange
# Use a non-interactive backend
import matplotlib
mat... |
"""An implementation of a basic Kalman with the bicycle motion model.
This module implements an "interface" for modules that pairs a filter type with
a motion model, and can thus be directly used to track objects.
"""
import numpy as np
from . import extended
NUM_STATES = 9
NUM_MEASUREMENTS = 4
# Default model nois... |
"""
CUDA driver bridge implementation
NOTE:
The new driver implementation uses a *_PendingDeallocs* that help prevents a
crashing the system (particularly OSX) when the CUDA context is corrupted at
resource deallocation. The old approach ties resource management directly
into the object destructor; thus, at corruptio... |
# pylint: disable=wildcard-import
__version__ = "3.4.1"
from .blocking import *
from .distributions import *
from .external import *
from .glm import *
from . import gp
from .math import logaddexp, logsumexp, logit, invlogit, expand_packed_triangular, probit, invprobit
from .model import *
from .stats import *
from .s... |
"""
Einfuhrzoll API
Abfragen von Importzöllen und Wechselkursen # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import io
import json
import logging
import re
import ssl
from urllib.parse import urlencode
import urllib3
from deutschland.zol... |
# input API arg spec json
# output ansible module option documentation skeleton
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import sys
import json
import yaml
arg_spec = json.load(sys.stdin)
def option_doc_from_arg_spec(spec, append_spec={}):
option_doc = {}
for ... |
import torch
import math
def calculate_matmul_n_times(n_components, mat_a, mat_b):
"""
Calculate matrix product of two matrics with mat_a[0] >= mat_b[0].
Bypasses torch.matmul to reduce memory footprint.
args:
mat_a: torch.Tensor (n, k, 1, d)
mat_b: torch.Tensor (1, k... |
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
ElementClickInterceptedException,
MoveTargetOutOfBoundsException,
ElementClickInterceptedException
)
from .move import move_button_to_viewport
import logging
def unretweet(driver, article):
try:
... |
#!/usr/bin/python3
##
## Licensed Material - Property of IBM
## (c) Copyright IBM Corp. 2017. All Rights Reserved.
##
import bluepy
import threading
import time
import re
import argparse
import sys
gworg = ''
gwdevtype = ''
gwdevid = ''
gwtoken = ''
# this name is the BTLE characteristic which gives the device typ... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from custom.views import group_required
from django.contrib.auth import authenticate, login
from django.utils.timezone import get_current_timezone
from django.contrib.auth.models import ... |
"""
=======================================================
Play a video in the 3D world
=======================================================
The goal of this demo is to show how to visualize a video
on a rectangle by updating a texture.
"""
from fury import window, actor
import numpy as np
import cv2
import time... |
# coding=utf-8
# --------------------------------------------------------------------------
# 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 ... |
df.groupby(['Pclass', 'Sex'])['Survived'].mean().to_frame()
|
# Generated from D:/AnacondaProjects/iust_compilers_teaching/grammars\AssignmentStatement3.g4 by ANTLR 4.8
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as bu... |
# Copyright 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://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying... |
"""
WSGI config for todolist project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Djan... |
r"""
.. role:: html(raw)
:format: html
Quantum advantage with Gaussian Boson Sampling
==============================================
.. meta::
:property="og:description": Using light to perform tasks beyond the reach of classical computers.
:property="og:image": https://pennylane.ai/qml/_images/... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File that houses all the entry points.There is currently only one entry point.
That entry point is run_server which starts up a scheduler and a variable
number of workers
"""
from multiprocessing import Process
import sys
from text_transformation.scheduler import Sche... |
from collections.abc import Iterable
from functools import reduce
import networkx as nx
from tensorflow import keras
from tensorflow.python.keras.utils.vis_utils import model_to_dot
from deephyper.core.exceptions.nas.space import (
InputShapeOfWrongType,
NodeAlreadyAdded,
StructureHasACycle,
WrongOutp... |
'#'"""
This script implements an example demonstrating the use of an SN-diagram to identify the
fatigue strenght for a material (steel, alloys, etc.)
Note, the SN-diagram is empirically determined. Thus, the fatigue strength is no gurantee
that a part will not fail.
The SN-diagram implementation can be found in file ... |
peso = float(input('Qual é o seu peso(Kg) ? '))
altura = float(input('Qual é a sua altura(m) ? '))
imc = peso / altura ** 2
print('O IMC dessa pessoa é de {:.1f}'.format(imc))
if imc < 18.5:
print('Você está ABAIXO do peso normal.')
elif imc < 25:
print('PARABÉNS, você está na faixa de PESO NORMAL!')
elif imc <... |
"""
WSGI config for ls project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setti... |
"""
Program to test image map-relative and view-relative placement.
Select which to show and experiment with placement parameters.
Usage: test_image_placement.py [-h|--help] [-d] [(-t|--tiles) (GMT|OSM)]
"""
import os
import sys
import wx
import pyslip
import pyslip.tkinter_error as tkinter_error
import pyslip.log a... |
#!/usr/bin/env python
# coding: utf8
# TODO
# при релимите - ссделать подпрограмку и испытывать через тулс на мелких и больших суммах
#
## при определнии адреса отправителя - если нет связи с кошельком..
## создавать 1 раз и потом оттуда брать а не каждый раз поновой искать
STARTUP_SHOP_ID = 6 # мой стартап ... |
# -*- coding: utf-8 -*-
"""The filter file CLI arguments helper."""
import os
from plaso.cli import tools
from plaso.cli.helpers import interface
from plaso.cli.helpers import manager
from plaso.lib import errors
class FilterFileArgumentsHelper(interface.ArgumentsHelper):
"""Filter file CLI arguments helper."""
... |
# -*- coding: utf-8 -*-
# TenderComplaintResourceTest
def create_tender_complaint(self):
response = self.app.post_json(
"/tenders/{}/complaints".format(self.tender_id),
{
"data": {
"title": "complaint title",
"description": "complaint description",
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
import torch
from fairseq im... |
import markovify
import config
from mlh_twitter_api import *
from twitter_scraper_fetcher import *
import random
import re
def generate_bot_answer_with_text_model(twitter_handle, user_question, text_model):
bot_answer = None
word_list = user_question.split(" ")
random_word = random.choice(wor... |
#!env/bin/python -u
# Main script for Adafruit Internet of Things Printer 2. Monitors switch
# for taps and holds, performs periodic actions (Twitter polling by default)
# and daily actions (Sudoku and weather by default).
# Written by Adafruit Industries. MIT license.
#
# MUST BE RUN AS ROOT (due to GPIO access)
#
... |
from __future__ import unicode_literals
default_app_config = 'document_parsing.apps.DocumentParsingApp'
|
import pytest
from astropy.io import fits
import numpy as np
from numpy.testing import assert_array_equal
from lightkurve import search_lightcurve
from lightkurve.io.tasoc import read_tasoc_lightcurve
from lightkurve.io.detect import detect_filetype
@pytest.mark.remote_data
def test_detect_tasoc():
"""Can we de... |
import logging
import numpy as np
from popmon.base import Module, Pipeline
class LogTransformer(Module):
_input_keys = ("input_key",)
_output_keys = ("output_key",)
def __init__(self, input_key, output_key):
super().__init__()
self.input_key = input_key
self.output_key = output_... |
# Utility functions for Psychopy Experiments
# Author: Stefan Uddenberg
from psychopy import core, data, event, gui
import json
import os
def tabify(s):
""" Takes an array of strings and
outputs a single string separated
by tab characters
:type s: list
:param s: list of strings
:raises: N/A
:rtype: string
"... |
# Copyright 2016 The Kubernetes Authors.
#
# 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 sys
import errno
import datetime
import itertools
from .commands import runCmd
class BaseDumper(object):
""" Base class to dump commands from host/target """
def __init__(self, cmds, parent_dir):
self.cmds = []
# Some testing doesn't inherit testimage, so it is needed
... |
# Optional list of dependencies required by the package
dependencies = ['torch']
# classification
from torchvision.models.alexnet import alexnet
from torchvision.models.densenet import densenet121, densenet169, densenet201, densenet161
from torchvision.models.inception import inception_v3
from torchvision.models.resne... |
""" Test portfolio end points """
import json
import os
import glob
from unittest.mock import patch
from unittest import mock
import pytest
from pinakes.main.catalog.permissions import (
PortfolioPermission,
)
from pinakes.main.models import Image
from pinakes.main.catalog.models import (
Portfolio,
Portf... |
from .meshes import *
from .tallies import build_tallies
from . import cuts
from . import plot
|
"""Auto-generated file, do not edit by hand. TG metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_TG = PhoneMetadata(id='TG', country_code=228, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[29]\\d{7}', possible_number_pattern='\\... |
# waelstow.py
__version__ = '0.10.2'
import contextlib, os, shutil, sys, tempfile, json
from unittest import TestCase, TestSuite, TestLoader
from six import StringIO
# =============================================================================
# Test Suite Discovery & Management
# =================================... |
# Import the required packages, with their conventional names
import matplotlib.pyplot as plt
import numpy as np
# Generate the data
x = np.arange(start=0, stop=10, step=0.2)
y = np.sin(x)
# Generate the plot
plt.plot(x, y)
# Display it on the screen
plt.savefig("Pyplot Style.png", bbox_inches='tight')
# %%
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
A setuptools-based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
Docs on the setup function kwargs:
https://packaging.python.org/distributing/#setup-args
"""
from __future__ import absolu... |
import os
import unittest
import pycodestyle
class TestPep8(unittest.TestCase):
"""Run PEP8 on all files in this directory and subdirectories."""
_exclude_dirs = ['subrepos', 'utility_scripts', '.venv']
def setUp(self):
self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))... |
import os,sys,io
import scipy.signal
from urllib.request import urlopen
from IPython.display import display, Audio, HTML, clear_output
import math
import numpy as np
import pandas as pd
import librosa
from .constants import EPS_FLOAT, LOG10, SIGEPS_FLOAT
import matplotlib as mpl
import matplotlib.pyplot as plt
im... |
import numpy as np
from math import floor
from torch.utils import data
class DataSplitter(data.Dataset):
"""
Subset dataset by index.
Helper class to be used with `train_valid_splitter`.
Parameters
----------
data : torch.utils.data.Dataset instance
length : int
Number of sampl... |
"""
Geometry factories based on the geo interface
"""
from point import Point, asPoint
from linestring import LineString, asLineString
from polygon import Polygon, asPolygon
from multipoint import MultiPoint, asMultiPoint
from multilinestring import MultiLineString, asMultiLineString
from multipolygon import MultiPoly... |
'''
Model file and non-differentially private file
'''
import time
import torch
import torch.nn.functional as F
from torch import nn, optim
import data
import utils
class EmbeddingNet(nn.Module):
def __init__(self, vocab_size: int, **_):
super().__init__()
# Embedding dimension: vocab_size + <un... |
"""
A ``multipla`` (which is spelled like ``Multi-plug``) is one of the italian
words for a power strip. As you probably know, most kind of ``multipla`` have
(multiple) sockets capable of handling mulitiple types of plugs. I thought it
would have been a perfect name for a module that helps developer to write and
use ex... |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose">
# Copyright (c) 2018 Aspose.Slides for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associa... |
from django.test import TestCase
from mock import patch
from casexml.apps.phone.tests.utils import call_fixture_generator
from corehq.apps.commtrack.tests.util import bootstrap_location_types
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.groups.exceptions import CantSaveException
from coreh... |
# -*- coding: utf-8 -*-
import unittest
from securetea.lib.log_monitor.system_log import utils
try:
# if python 3.x.x
from unittest.mock import patch
except ImportError: # python 2.x.x
from mock import patch
class TestUtils(unittest.TestCase):
"""
Test class for utils.
"""
@patch("secur... |
import base64
import json
import pathlib
import re
from simple_salesforce.exceptions import SalesforceMalformedRequest
from cumulusci.core.exceptions import CumulusCIException
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
def join_errors(e: SalesforceMalformedRequest) -> str:
return "; ".join([er... |
import tensorflow as tf
from tensorflow.python.client import device_lib
def scatter_update(ref, indices, updates):
"""Update the value of `ref` at indecies to `updates`.
"""
return tf.scatter_update(ref, indices, updates)
def hasGPU():
devs = device_lib.list_local_devices()
return any([dev.device_... |
#!/usr/bin/env python
import ROOT
import AtlasStyle
from array import array
ROOT.gROOT.SetBatch()
if not hasattr(ROOT, "myText"):
ROOT.gROOT.LoadMacro("$HZZWSCODEDIR/scripts/loader.c")
def get_graph(file_name):
mass_list = []
obs_list = []
exp_list = []
gr_obs = None
gr_exp = None
with o... |
# Generated by Django 2.0.3 on 2018-03-17 17:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("wagtailimages", "0019_delete_filter"),
]
operations = [
migrations.AlterModelOptions(
name="image",
options={"verbose_name":... |
from unittest import TestCase
from mock import patch
from regulations.views import reg_landing
class LandingViewTest(TestCase):
@patch('regulations.views.reg_landing.api_reader')
def test_regulation_exists_not(self, api_reader):
api_reader.ApiReader.return_value.regversions.return_value = None
... |
import torch
import random
import numpy as np
import pytest
from geoopt.manifolds import lorentz
@pytest.fixture("module", autouse=True, params=range(30, 40))
def seed(request):
seed = request.param
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
return seed
@pytest.fixture("modul... |
# -*- coding: utf-8 -*-
# Copyright (C) 2022 Antmicro
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.