content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
import mir_eval
import bss_eval_base
class BSSEvalSources(bss_eval_base.BSSEvalBase):
"""
"""
def __init__(self, true_sources_list, estimated_sources_list, source_labels=None, algorithm_name=None,
do_mono=False,... |
import numpy as np
import matplotlib.pyplot as plt
from lyapy import lyapy
import corner as triangle
from matplotlib.ticker import NullFormatter,MultipleLocator, FormatStrFormatter, MaxNLocator
import time
from astropy.modeling.models import Voigt1D, Lorentz1D, Gaussian1D
from matplotlib import gridspec
plt.ion()
d... |
#!/usr/bin/env python
# Copyright 2014, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
|
#!/usr/bin/env python
import sys, os, yaml, time, urllib2, atexit, signal
import logging
from helpers.keystore import Etcd
from helpers.postgresql import Postgresql
from helpers.ha import Ha
from helpers.ascii import splash, showtime
LOG_LEVEL = logging.DEBUG if os.getenv('DEBUG', None) else logging.INFO
logging.ba... |
n = int(input("Digite o valor de n: "))
i = 0
while i < n:
print(2*i+1)
i = i + 1 |
# -*- coding: utf-8 -*-
"""Utility functions for mkpyproject
"""
from typing import Optional
import os
import re
from datetime import datetime
import logging
def _get_logger() -> logging.Logger:
"""Creates a logger
"""
logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
ch.setLevel(l... |
"""
Classes from the 'CoreMIDI' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
MIDINetworkConnection = _Class("MIDINetworkConnection")
MID... |
from .entities import Compound, Entity, Class, File, Struct, Namespace
from . import xml
import os
from typing import List, Dict
class ParserBase:
def __init__(self, xmldir : str):
self._xmldir = xmldir
def _reffile(self, refid : str) -> str:
return os.path.join(self._xmldir, refid+".xml")
... |
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
|
from spatialfilter import CAR, Whitening, SymWhitening, CSP, Deflate
from timefreq import TFC
from filter import Filter, OnlineFilter, Winsorize
from window import SlidingWindow, OnlineSlidingWindow
from wrapper import Decimate, Slice
from nonstat import SlowSphering
|
#!/usr/bin/env python
"""
requests_cache.core
~~~~~~~~~~~~~~~~~~~
Core functions for configuring cache and monkey patching ``requests``
"""
from contextlib import contextmanager
from datetime import datetime, timedelta
from operator import itemgetter
import requests
from requests import Session as Origina... |
#!/usr/bin/env nosetests
import os
import imp
import shutil
import subprocess
import muterl_lex
import muterl_logic
import muterl_clause
import muterl_constants
if os.path.isdir('test_tmp'):
shutil.rmtree('test_tmp')
good_sources = [{'name': 'jsx',
'git': 'https://github.com/talentdeficit/jsx',
... |
from .run import run_pauli_expectation
from .resolution import build_quasar_circuit
from .circuit import Circuit
import numpy as np
import itertools
class Tomography(object):
def __init__(self):
raise NotImplementedError
@property
def nparam(self):
raise NotImplementedError
... |
from datetime import datetime, timedelta
from flask import Flask
from flask_cors import CORS
from flask_jwt_simple import JWTManager
from uranus_middleware.auth_utils import JWT_SECRET_KEY
from uranus_middleware.endpoints import init_app
from uranus_middleware.resources import (
airport, auth, boarding_pass, ch... |
# -*- coding: utf-8 -*-
"""Clothing data provider."""
from mimesis.providers.base import BaseProvider
__all__ = ['Clothing']
class Clothing(BaseProvider):
"""Class for generate data related to clothing."""
class Meta:
"""Class for metadata."""
name = 'clothing'
def international_size... |
import traceback
class FunctionCollection:
"""
Args:
on_error: function, launched when function in collection raises an
exception
on_error_kwargs: additional kwargs for on_error function
include_exceptions: include exceptions into final result dict
"""
def ... |
"""
Copyright (C) 2021 Adobe.
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) any later version.
This program is distributed in the hope that it w... |
# coding: utf-8
#
# Copyright 2016 The Oppia 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 requi... |
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
print ("current_dir=" + currentdir)
parentdir = os.path.join(currentdir,"../gym")
os.sys.path.insert(0,parentdir)
import pybullet as p
import pybullet_data
import time
import csv
#########---------------START Ob... |
# coding=utf-8
from tgbot import plugintest
from plugin_examples.bold import BoldPlugin
class AdminPluginTest(plugintest.PluginTestCase):
def setUp(self):
self.bot = self.fake_bot('', inline_query=BoldPlugin())
def test_inline(self):
self.receive_inline(u'hello')
results = self.pop_re... |
'''Helper for plotting reblocking plots.'''
# copyright: (c) 2015 James Spencer
# license: modified BSD license; see LICENSE for further details.
import matplotlib.pyplot as plt
def plot_reblocking(block_info, plotfile=None, plotshow=True):
'''Plot the reblocking data.
Parameters
----------
block_info : :class:... |
import numpy as np
from rlkit.torch.core import eval_np
def marollout(
env,
agent_n,
max_path_length=np.inf,
render=False,
render_kwargs=None,
shared_obs=False,
shared_encoder=None,
shared_groups=None,
collect_raw_actions=False,
):
"""
The... |
# we are using webcam .
import cv2
import numpy as np
cap = cv2.VideoCapture(0) # we are accessing first webcam of the system
# cap = cv2.VideoCapture(1) # to access for second webcam
while True:
ret , frame = cap.read()
cv2.imshow ('WebCam',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
... |
import discord, sqlite3, asyncio
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
from discord_slash.utils.manage_commands import create_option
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(name="pollend", description="Terminer un... |
# -*- coding: utf-8 -*-
"""
Unfinished non-wbia dependent version of interact matches
"""
import utool as ut
import numpy as np
from wbia.plottool import abstract_interaction
BASE_CLASS = abstract_interaction.AbstractInteraction
# TODO: move to plottool and decouple with IBEIS
# TODO: abstract interaction
@ut.reload... |
from django.shortcuts import render
from .braille_translators import alphaToBraille, brailleToAlpha
def braille_viewer(request):
text = "This is how they see the world."
text_braille = alphaToBraille.translate(text)
print(text_braille)
braille_text = brailleToAlpha.retranslate(text_braille)
... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 applic... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ocrProfileNameDialog.ui'
#
# Created by: PyQt5 UI code generator 5.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ocrNameDialog(object):
def setupUi(self, ocrNameDialo... |
# -*- coding: utf-8 -*-
"""
Halma
@author: Mursito
"""
from halma_model import HalmaModel
model = HalmaModel()
model.awal(0,0)
p = model.getPapan()
print("PAPAN---------------------------")
print(p)
b0 = model.getPosisiBidak(1)
print("POSISI BIDAK---------------------------")
print(b0)
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial, time
class SyncError(Exception):
"""Synchronisation error"""
def __init__(self, msg=""):
self._msg = str(msg)
def __str__(self):
return msg
class SerialRGB(object):
"""Easy controlling of the RGB-LED / Arduino"""
def __init__(self, addr, baud=96... |
"""
`Model` class for running the LPD model.
"""
import importlib
import math
import warnings
from copy import deepcopy as copy
import numpy as np
from . import lpd
from .utils import disable_numba
from .utils import enable_numba
from .utils import numbify
from .utils import unnumbify
__all__ = (
"Model",
"... |
from PIL import Image
from colormap import *
import os
def image_read(img_s):
img = Image.open(img_s)
largeur,hauteur = img.size
l=[]
cou=largeur*hauteur
for y in range(hauteur):
for x in range(largeur):
r,v,b = img.getpixel((x,y))
rgb565 = (((r & 248)<<8)+((v & 252)<<3)+((b & 248)>>3))
#print(hex(rgb... |
#!/usr/bin/python3
a, b = 0, 10
while a < b:
print(a)
a = a + 1
print('Done') #Here this line also is a part of While loop
for i in range(1,10):
print(i)
#Example of iterating through array
bridgera = ['Arijit','Soumya','Gunjan','Arptia','Bishwa','Rintu','Satya','Lelin']
for i in range(len(... |
from collections import defaultdict
import tldextract
from extensionanalysis import chromecast_extension_ids
from query import Query
class QueryWar(Query):
def query_war_schemes(self) -> list:
"""Get the number of WAR requests and the number of websites performing WAR requests grouped per URL scheme"""
results... |
#!/usr/bin/python
# tv_sort.py
# detects and sorts tv shows automatically based on filename
import os
import shutil
import re
import xmlrpclib
words = r'([\'\w\.\- ]+?)'
spacers = re.compile(r'[\s_\-\.]+')
show_filename = re.compile(words + r'S(\d+)\s?EP?(\d+)', re.IGNORECASE)
show_filename_2 = re.compile(words + r'... |
# Train a model
# +
import pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn_evaluation import plot
# + tags=["parameters"]
upstream = ['join']
product = None
# -
df = pd.... |
# importar pacotes
import pandas as pd
import pydeck as pdk
import streamlit as st
# import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# from datetime import date
# carregar os meus dados
df = pd.read_csv('kc_dataset_clean.csv')
# dashboard
st.title("Casas em Seattle")
st.markdo... |
#!/usr/bin/env python3
#
# Copyright 2019 Peifeng Yu <peifeng@umich.edu>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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 L... |
from os.path import join
import logging
from glob import glob
from vcstools.config import load_config_file
from vcstools.job_submit import submit_slurm
from dpp.helper_files import glob_pfds
comp_config = load_config_file()
logger = logging.getLogger(__name__)
def submit_prepfold_products_db(cfg, dep_id=None, dep_t... |
import knapsack
import time
"""
This script is used to debug the knapsack solver in python/knapsack.py
"""
def main():
# setup libknapsack object
capacity = 5
ks = knapsack.Knapsack(capacity)
# add items to knapsack
ks.addItem(3,10)
ks.addItem(1,2)
ks.addItem(2,2)
ks.addItem(1,3)
# ... |
# -*- coding: utf-8 -*-
"""Top-level package for Vehicle History Reports."""
__author__ = """Mpho Mphego"""
__email__ = "mpho112@gmail.com"
from vehicle_history_reports.vehicle_history_reports import *
|
import os
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.distributions import Categorical
import matplotlib.pyplot as plt
env = gym.make("CartPole-v0")
env.reset()
class Policy(nn.Module):
... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
#import module_mass file as a pd.DataFrame and name column
input = pd.read_csv('input.txt', header = None)
input.columns = ['module_mass']
#calculate fuel needed
input['fuel'] = (input['module_mass']/3)
input['fuel_round']= input['fuel'].apply(np.floor)
i... |
"""Canny tap class."""
from pathlib import Path
from typing import List
from singer_sdk import Tap, Stream
from singer_sdk.typing import (
DateTimeType,
PropertiesList,
Property,
StringType,
)
from tap_canny.streams import (
BoardsStream,
PostsStream,
StatusChangesStream,
TagsStream,
... |
import numpy as np
import pandas as pd
from netCDF4 import Dataset
from sklearn.pipeline import Pipeline
from analysis.data import GeographicArea
from sklearn.metrics import davies_bouldin_score
class Sink:
def __init__(self, pipeline: Pipeline, area: GeographicArea):
self.pipeline = pipeline
self... |
from lightwood.encoders.categorical.categorical import CategoricalEncoder
default = CategoricalEncoder |
import io
import os
import sys
import json
import glob
import shutil
import inspect
import pathlib
import tarfile
import tempfile
import unittest
import contextlib
import dataclasses
import unittest.mock
from typing import Type, List, BinaryIO
from dffml.version import VERSION
from dffml.df.types import DataFlow
from ... |
#!/bin/env python3
"""
This is an example script to tokenize or detokenize batch data using CSV file.
Usage: batch_tokenize_and_detokenize.py [options]
Tokenize or Detokenize using CSV file. Please make sure you have updated
envvars file
Options:
-h, --help show this help message and exit
--csv_file_... |
"""Tests for distos.stencil
"""
import sys
sys.path.insert(1, "..")
import unittest
import sympy as sp
import numpy as np
import random
from dictos.spec import DEFAULT_INTERVAL, DEFAULT_DIFFERENTIAND
from dictos.stencil import (
create_coordinate_symbols,
create_differentiand_symbols,
to_subscript,
g... |
from setuptools import setup
setup(name='stormtrooper',
version='0.0.1',
description='Report trooper status and geolocation using homomorphic encryption',
url='bitbucket.com',
author='Jonathan Pinto Barbosa',
author_email='jonathanpbarbosa@gmail.com',
license='MIT',
packages=[... |
import cffi
ffi = cffi.FFI()
ffi.cdef("const int mysize;")
lib = ffi.verify("const int mysize = sizeof(long long int);")
print(lib.mysize)
|
from .models import Resource, Reservation
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
#
# Conflict
#
class Conflict():
def __init__(self, conflicting_reservations, val_error):
self.conflicting_reservations = conflicting_reservations
self.val_erro... |
from picoborgrev.PicoBorgRev import PicoBorgRev
from calibrate_tracks import get_char
import sys
class basic_controls():
def __init__(self):
self.ctl = PicoBorgRev()
self.ctl.Init()
def go(self, power=0.25):
self.ctl.SetMotors(power)
def stop(self):
self.ctl.SetMotors(0)
... |
load("@build_stack_rules_proto//:plugin.bzl", "ProtoPluginInfo")
load("@protobuf_py_deps//:requirements.bzl", protobuf_requirements = "all_requirements")
load("@grpc_py_deps//:requirements.bzl", grpc_requirements = "all_requirements")
load(
"@build_stack_rules_proto//:aspect.bzl",
"ProtoLibraryAspectNodeInfo",
... |
import pytest
from tests.support.asserts import assert_error, assert_success
def element_click(session, element):
return session.transport.send(
"POST", "session/{session_id}/element/{element_id}/click".format(
session_id=session.session_id,
element_id=element.id))
def test_disp... |
def auto_loop_setup():
try:
import uvloop # noqa
except ImportError: # pragma: no cover
from uvicorn.loops.asyncio import asyncio_setup as loop_setup
loop_setup()
else:
from uvicorn.loops.uvloop import uvloop_setup
uvloop_setup()
|
import numpy as np
from sweref99 import projections
from kmm.positions.positions import Positions
tm = projections.make_transverse_mercator("SWEREF_99_TM")
def geodetic(positions: Positions):
dataframe = positions.dataframe
if len(dataframe) == 0:
dataframe = dataframe.assign(longitude=[], latitude... |
# Copyright 2020 The OpenAGI Datum 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 ... |
# Copyright 2021 Zilliz. 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 applicable law or agree... |
"""
"""
## python imports
from random import randint
## source.python imports
from effects.base import TempEntity
from engines.sound import StreamSound
from engines.precache import Model
from entities.entity import Entity
from filters.players import PlayerIter
from listeners.tick import Repeat
from weapons.manager... |
from .text_classifier import TextClassifier # noqa
|
#!/usr/bin/env python
# Import modules
import numpy as np
from visualization_msgs.msg import Marker
import rospy
import tf
from geometry_msgs.msg import Pose
from std_msgs.msg import String
from franka_description.srv import *
# function to load parameters and request PickPlace service
def franka_mover():
# TODO... |
import pygame
pygame.init()
pygame.mixer.music.load('Desafio21.mp3')
pygame.mixer.music.play()
while pygame.mixer.music.get_busy(): pass |
#!/usr/bin/env python
#________INDEX____________.
# |
# 6 functions |
# (6=3+2+1) |
# |
# -3 auxiliary |
# -2 plots) |
# -1 main) |
# |
# (if __name__==__main__) |
#________________... |
from zotapaysdk.mg_requests.objects import MGRequestParam
from zotapaysdk.mg_requests.mg_request import MGRequest
class MGPayoutRequest(MGRequest):
# pylint: disable=missing-function-docstring
def __init__(self, **kwargs):
self._merchant_order_id = \
MGRequestParam(self.PayoutRequestParame... |
import re
from omnibot.services import slack
from omnibot.services import stats
def extract_users(text, bot):
statsd = stats.get_statsd_client()
with statsd.timer('parser.extract_users'):
# Example: <@U024BE7LH> or <@U024BE7LH|bob-marley> or <@W024BE7LH|bob-marley>
user_arr = {}
users... |
from chill import *
source('datacopy34.c')
destination('datacopy4modified.c')
procedure('mm')
loop(0)
original()
tile(0,3,16)
datacopy([(0,[0,1])],4)
print_code()
|
# import the main panels structure, required
from ..panels import boxPanel
# import here your procedure-specific modules, no requirements (numpy as an example)
from scipy.signal import savgol_filter
# Set here the details of the procedure
NAME = 'SavGol' # Name, please keep it short as it will appear in the combo box... |
r"""Functions for exclusive $D\to P\ell\nu$ decays.
Copied from `flavio.physics.bdecays.bplnu`
"""
from math import sqrt
import flavio
from flavio.physics import ckm
from flavio.classes import AuxiliaryQuantity
from flavio.config import config
from flavio.physics.running import running
from flavio.physics.bdecays imp... |
import json
from ingest import ingest_json_body
from housepy import config, log, strings, util
def parse(request):
log.info("ambit.parse")
sample = ingest_json_body(request)
if sample is None:
return sample, "Could not parse"
data = {}
for key, value in sample.items():
if key == "... |
from typing import List, Union
import torch
from torch import nn, optim
from torch.distributions import Distribution
from tqdm import tqdm
class GeneralizedMixtureModel(nn.Module):
def __init__(self,
distributions: List[nn.Module],
max_iter=1000,
rtol=1e-8,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__Author__ = Warsong
#_PlugName_ = 万户ezeip任意文件下载
#_Function_ = 插件格式
#_FileName_ = whezeip_Download_Anything.py
def assign(service, arg):
if service == "whezeip":
return True, arg
def audit(arg):
payload='download.ashx?files=../web.config'
... |
import pandas as pd
import logging
from typing import Union
from pathlib import Path
from ecat.tables import reimport_log, reimport, product_code
from ecat.db import Connections
from ecat.classroom import artikel
from ecat.analysis import generate_analysis, compare_data
from ecat.sql import get_template_config, render_... |
import torch
class RBM:
def __init__(self, visible_dim, hidden_dim):
self.weights = torch.randn(hidden_dim, visible_dim)
self.hidden_bias = torch.randn(1, hidden_dim)
self.visible_bias = torch.randn(1, visible_dim)
def sample_hidden(self, input):
weighted_input = torch.mm(... |
#
# -*- coding: utf-8 -*-
#
# This file is part of reclass
#
from reclass.values import item
from reclass.utils.dictpath import DictPath
from reclass.errors import ResolveError
class RefItem(item.ItemWithReferences):
type = item.ItemTypes.REFERENCE
def assembleRefs(self, context={}):
super(RefItem,... |
from torchvision.models.resnet import ResNet, BasicBlock, Bottleneck
import torch
from torch import nn
class ResNet_LJ(nn.Module):
def __init__(self, model_name, is_FC = True):
super().__init__()
if model_name == 'resnet18':
basic_model = ResNet(block=BasicBlock, layers=[2,2,2,2])
... |
import sys
sys.path.insert(0,'./fms/lambda/global-accelerator-protection')
import boto3
import os
import botocore
import logging
import json
import copy
import cfnresponse
from tag_check import tag_check
logger = logging.getLogger('shieldProtection')
logger.setLevel('DEBUG')
ga_client = boto3.client('globalaccelerat... |
def integral(a_i, h, n):
integ = 0.0
for j in range(n):
a_ij = a_i + (j + 0.5) * h
integ += cos(a_ij) * h
return integ
|
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
|
import tempfile
import yaml
from utils import shell
import os
import logging
class CloudInit(object):
def __init__(self, run_qcow_path):
self.iso_base_path = run_qcow_path
def _write_metadata(self, vm, filepath):
with open(filepath, 'w') as f:
f.write("instance-id: %s\n" % vm.name... |
from cdocs.simple_config import SimpleConfig
import unittest
class ConfigTests(unittest.TestCase):
noise = False
def _print(self, text:str) -> None:
if self.noise:
print(text)
def off(self) -> bool:
return False
def test_get_config_items(self):
self._print(f"Confi... |
#!/usr/bin/env python
from __future__ import print_function
default_pars = {'nx1': (int,128),
'nx2': (int,1),
'nx3': (int,1),
'nscalars': (int,0),
'gamma' : (float,1.4),
'cfl' : (float,.2),
'x1_min': (float,0.),
'x1_max': (float,1.),
'x2_min': (float,0.),
... |
"""create a comment on differential reviews.
usage examples:
comment on revision '1':
$ arcyon comment 1 -m 'hello revision 1, how are you?'
accept revision '1':
$ arcyon comment 1 -m 'looks good' --action accept
comment on revisions 1 and 2, reading the message from 'mymessage':
$ arcyon com... |
def section1():
"""
# Upload & Manage Data & Metadata
## Upload specific files
When you have specific files you want to upload, you can upload them all into a dataset using this script:
"""
def section2():
"""
## Upload all files in a folder
If you want to upload all files from a fol... |
#First Way !!
#import myfunc
#myfunc.hello()
# Second way
from myfunc import hello
hello
# third way - import dir into path
#/Users/mohalloran/Documents/Python_For_NetENG_with_KirkB/PROGRAMS/week2/test
|
#!/usr/bin/env python
from typing import List
import numpy as np
from pyems.pcb import common_pcbs
from pyems.simulation import Simulation
from pyems.utilities import print_table
from pyems.structure import (
PCB,
Microstrip,
common_smd_passives,
SMDPassive,
)
from pyems.coordinate import Box2, Coordin... |
import os
from pathlib import Path
from subprocess import run, PIPE
import pytest
from conftest import bake_project, config_generator
def no_curlies(filepath):
""" Utility to make sure no curly braces appear in a file.
That is, was jinja able to render everthing?
"""
data = filepath.open('r').re... |
"""
Original: Shelley Pham
New Author: Shubham Naik
"""
from __future__ import print_function
import httplib2
import os
import re
import time
import base64
from apiclient import discovery
from apiclient import errors
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
... |
# Copyright 2015 Red Hat, 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 applicable law ... |
from OSMPythonTools.overpass import Overpass, overpassQueryBuilder
from OSMPythonTools.nominatim import Nominatim
import argparse
import pprint
import sys
highway_roads = ['motorway', 'trunk', 'primary', 'secondary', 'tertiary', 'unclassified', 'residential']
highway_link_roads = ['motorway_link', 'trunk_link', 'prima... |
# coding=utf-8
"""
Project Euler Problem 33
Digit cancelling fractions
Solved by Ahrar Monsur
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractio... |
import numpy as np
from skimage.color import gray2rgb
from skimage.draw import (
circle,
circle_perimeter,
circle_perimeter_aa
)
from skimage.morphology import (
dilation,
disk
)
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Arena(QObject):
"""Base class fo... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()... |
from datetime import date
from django.db.models import Prefetch
from wagtail.core import blocks
from regulations3k.models.django import EffectiveVersion
from v1.atomic_elements import organisms
class RegulationsList(organisms.ModelBlock):
model = "regulations3k.RegulationPage"
ordering = "title"
headi... |
#
# Copyright(c) 2022 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
from threading import Lock
from .volume import Volume, VOLUME_POISON
from .io import Io, IoDir
from ctypes import cast, c_void_p, CFUNCTYPE, c_int, POINTER, memmove, sizeof, pointer
class ReplicatedVolume(Volume):
def __init__(self... |
# For balanced binary tree, will be O(n*log(n)) because
# max path depth is O(log(n)) due to height of tree.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def dfs(self, goal, all_paths, curr_path=None):
if cu... |
"""
Unit test for Utils
"""
import os
from unittest import TestCase
from unittest.mock import patch, Mock
from samcli.local.docker.utils import to_posix_path, find_free_port
from samcli.local.docker.exceptions import NoFreePortsError
class TestPosixPath(TestCase):
def setUp(self):
self.ntpath = "C:\\Use... |
import math
import json
import argparse
import sys
class Customer:
def __init__(self, user_id, name, latitude, longitude):
self.user_id = int(user_id)
self.name = name
self.latitude = float(latitude)
self.longitude = float(longitude)
def __repr__(self):
return '{} {}:... |
#!/usr/bin/python
import unittest
import os
import sys
from swiftclient import client
import paramiko
hostname = "127.0.0.1"
port = 8022
# setup logging
#paramiko.util.log_to_file('test_sftpd.log')
class SftpcloudfsTest(unittest.TestCase):
''' FTP Cloud FS main test '''
def setUp(self):
if not all([... |
import math
import supervisely_lib as sly
class SlyProgress:
def __init__(self, api, task_id, pbar_element_name):
self.api = api
self.task_id = task_id
self.pbar_element_name = pbar_element_name
self.pbar = None
def refresh_params(self, desc, total, is_size=False):
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.