text stringlengths 1 927k |
|---|
import pytest
from ctypes import *
unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong]
signed_types = [c_byte, c_short, c_int, c_long, c_longlong]
float_types = [c_double, c_float, c_longdouble]
try:
c_ulonglong
c_longlong
except NameError:
pass
else:
unsigned_types.append(c_ulonglong)
signed_t... |
import logging
from time import time
import pyspedas
from pyspedas import time_double
from pyspedas.mms.particles.mms_part_products import mms_part_products
logging.captureWarnings(True)
logging.basicConfig(format='%(asctime)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
def mms_part_getspec(inst... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Yahoo! Finance market data downloader (+fix for Pandas Datareader)
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test block processing.
This reimplements tests from the bitcoinj/FullBlockTestGenerator used
by the pu... |
import logging
import os
from collections import (
defaultdict,
namedtuple,
)
from galaxy import exceptions
from galaxy.util import (
plugin_config
)
log = logging.getLogger(__name__)
FileSourcePath = namedtuple('FileSourcePath', ['file_source', 'path'])
class ConfiguredFileSources:
"""Load plugins... |
from .nf import GeneratorLimitExceeded, symmGB_F2_C, symmGB_F2_python
from .PyPolyBoRi import (Monomial, Polynomial,
GroebnerStrategy, OrderCode, ll_red_nf_redsb)
from .ll import eliminate, ll_encode
from copy import copy
from itertools import chain
from .statistics import used_vars_set
from .h... |
# encoding: utf-8
from django.conf.urls import patterns, url
from admin_helper.views import PopupView, SuggestView
urlpatterns = patterns(
'admin_helper.views',
url(r'^suggest/$', SuggestView.as_view(), name='suggest'),
url(r'^popup/$', PopupView.as_view(), name='popup')
) |
# %%
#######################################
def pandasread_csv_addheader(csv_file: str, addheader: list):
"""Returns a pandas dataframe from the given .csv file. Assumes there is no header in the .csv and requires a header to be given as an argument to the 'addheader'.
Example:
>>> myheader = ['NAME'... |
#!/usr/bin/env python3
"""Usage:
test.py FILE
test.py -h --help
"""
import sys
import os.path
from docopt import docopt
from backtest.oanda_backtest import OandaBacktest
from logic.strategy import Strategy
from settings import CANDLES_MINUTES, MAX_PERCENTAGE_ACCOUNT_AT_RISK,\
STOP_LOSS, TRAILING_PERIOD, TAKE_PR... |
"""
Adapted from guacamol_baselines https://github.com/BenevolentAI/guacamol_baselines
"""
import logging
from typing import List
import torch
#from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from model import SmilesRnn
from trainer import SmilesRnnTrainer
from utils import get_ten... |
# Generated by Django 3.1.5 on 2021-02-08 08:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('db', '0022_student_nickname'),
]
operations = [
migrations.AddField(
model_name='student',
name='field_of_study',
... |
# Author: Navonil Das (@NavonilDas)
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may no... |
from urllib.parse import urlencode
from urllib.request import urlopen
from time import time
from json import load
from codecs import getreader
from os import environ
reader = getreader("utf-8")
token = environ['SLACK_TEST_TOKEN'] # Uses legacy test API token - TODO: This will need to be updated
days = 14 # Purge fi... |
# -*- coding: utf-8 -*-
import re
import os
import unix
import weakref
from .. import Linux, Chroot, LinuxError
from unix.linux.services import Initd, Upstart, Systemd
DISTRIBS = ('RedHat', 'CentOS')
_CONFDIR = '/etc/sysconfig'
_NETFILE = os.path.join(_CONFDIR, 'network')
def RedHat(host, force=False):
unix.is... |
from _dependencies.graph import _Graph
class _LazyGraph:
def __init__(self, attrname, namespace):
self.attrname = attrname
self.namespace = namespace
def __get__(self, instance, owner):
graph = _Graph()
for base in reversed(owner.__bases__):
graph.update(base.__dep... |
"""
The base top-level plot model class.
From this all data and plotting flow.
"""
from pageplot.exceptions import PagePlotParserError
from pathlib import Path
from typing import Any, Optional, Dict, List, Union
from pageplot.extensionmodel import PlotExtension
from pageplot.extensions import built_in_extensions
fro... |
from flask import request, jsonify
from jdxapi.utils.logger_resource import LoggerResource
from jdxapi.app import api, DB
from jdxapi.models import Pipeline
from jdxapi.utils.functions import RequestHandler, ResponseHandler
from jdxapi.utils.error import ApiError
from sqlalchemy.orm.exc import NoResultFound, MultipleRe... |
from __future__ import unicode_literals
import json
import re
from collections import defaultdict
from moto.core.responses import BaseResponse
from moto.core.utils import camelcase_to_underscores
from .models import sns_backends
from .exceptions import InvalidParameterValue, SNSNotFoundError
from .utils import is_e164... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
import random
from itertools import product, repeat
import numpy as np
import tensorflow as tf
from cleverhans.attacks import SPSA
from cleverhans.model import Model
from foolbox.attacks... |
SDL2_LOADER = None
SDL2_TTF_LOADER = None
SDL2_IMG_LOADER = None
SDL2_GFX_LOADER = None
SDL2_API_NAMES = []
SDL2_API_ARGS_MAP = {}
SDL2_API_RETVAL_MAP = {}
SDL2_TTF_API_NAMES = []
SDL2_TTF_API_ARGS_MAP = {}
SDL2_TTF_API_RETVAL_MAP = {}
SDL2_IMG_API_NAMES = []
SDL2_IMG_API_ARGS_MAP = {}
SDL2_IMG_API_RETVAL_MAP = {}
... |
import threading
import traceback
from camera.sdk_gige_hikvision.GrabImage import MVS_Cam # 工业相机SDK读流
class hikCamera(threading.Thread):
def __init__(self, ip_name):
threading.Thread.__init__(self)
self.ip_name = ip_name
# 初始化摄像头
self.device_camera = MVS_Cam(self.ip_name)
... |
#!/usr/bin/env python
#encoding: utf8
import unittest, rostest
import rosnode, rospy
import time
from pimouse_ros.msg import MotorFreqs
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse #追加
from pimouse_ros.srv import TimedMotion
class MotorTest(unittest.TestCase):
def setUp(se... |
#winKernel.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2019 NV Access Limited, Rui Batista, Aleksey Sadovoy, Peter Vagner, Mozilla Corporation, Babbage B.V., Joseph Lee
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""Functions that wrap Windows ... |
from test_helpers import helper_get_katsu_response
from test_helpers import helper_get_user_token
import pytest
"""
This test suite will cover the manual testsfor KATSU in README.md, ensuring that
authorization happens correctly
- beacon permissions
- registered/controlled access
- modified but live token
"""
KATSU_U... |
"""
Django settings for evalai project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import dat... |
# Copyright 2016 Hewlett Packard Enterprise Software, LLC
# 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 requ... |
lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end=" ")
for j in range(0, 10):
print(j, end=" ") |
#!/usr/bin/env python3
"""
l0m1s
lukes1582@gmail.com
algoritmo insertion sort sviluppato per Python
"""
arr = [5,4,3,1,2,11,9,8,0]
print("Array in origine ")
print(arr)
print ("Lunghezza dell'array "+ str(len(arr)))
print(50*"x")
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < ar... |
#!/usr/bin/env python3
#
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Handles Whale's button click event."""
import argparse
import functools
import logging
import os
import re
import sys
import ... |
import numpy as np
class SelfishAgent(object):
def __init__(self, T):
self.T = T
self.policy = np.asarray([
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 2, 0, 0, 0, 0, 0, 0],
[2, 1, 2, 2, 2, 0, 0, 0, 0],
[2, 2, 1, 2, 2, 2, 0, 0, 0],
[2, 2, 2, 1... |
from copy import deepcopy
from openpnm.core import Subdomain, ModelsMixin, ParamMixin
from openpnm.utils import Docorator, SettingsAttr
from openpnm.utils import Workspace, logging
logger = logging.getLogger(__name__)
ws = Workspace()
docstr = Docorator()
@docstr.get_sections(base='GeometrySettings', sections=['Param... |
# Copyright 2017-present Open Networking Foundation
#
# 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 agr... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
import argparse
import csv
import importlib
from core_data_modules.cleaners import Codes
from core_data_modules.logging import Logger
from core_data_modules.traced_data.io import TracedDataJsonIO
from src.engagement_db_to_analysis.membership_group import (get_membership_groups_data)
log = Logger(__name__)
if __nam... |
import requests
from bs4 import BeautifulSoup
# Taking City You Want to Check Temperaature
city = input("Enter City : ")
# Storing City You Want to Check Temperaature
search = "weather in" + city
# Searching it on google
url = f"https://www.google.com/search?&q={search}"
# Sending and Receiving Requests
r = requests.g... |
"""
Physical units and dimensions.
The base class is Unit, where all here defined units (~200) inherit from.
The find_unit function can help you find units for a given quantity:
>>> import sympy.physics.units as u
>>> u.find_unit('coul')
['coulomb', 'coulombs']
>>> u.find_unit(u.charge)
['C', 'ch... |
from __future__ import absolute_import, unicode_literals
from django_pg.utils.south import south_installed
import os
import sys
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Database settings. This assumes that the default user and empty
# password will work.
DATABASES = {
'default': {
'ENGINE': 'django.db.back... |
import urlparse
from django.conf.urls.defaults import url
from canvas.exceptions import ServiceError
re_slug = lambda name: "(?P<%s>[a-zA-Z0-9_.,-]+)" % name
re_group_slug = lambda name: "(?P<%s>[-a-zA-Z0-9_]+)" % name
re_int = lambda name: "(?P<%s>\d+)" % name
re_year = re_int('year')
re_month = re_year + "/" + re... |
# Copyright 2019 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
import subprocess
from pathlib import Path
from random import Random
from immutablecollections import immutableset
from vistautils.parameters import Parameters
from pegasus_wrapper import PegasusProfile
from pegasus_wrapper.artifact import ValueArtifact
from pegasus_wrapper.locator import Locator, _parse_parts
from p... |
from flask import Blueprint, render_template,request, jsonify
from rdflib.term import Literal
from . import utils, model
bp = Blueprint('endpoint', __name__)
@bp.route('/endpoint')
def endpoint():
print "received request"
q=request.json['query']
res = utils.kb.query(q, initNs=utils.namespaces)
res_lis... |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import torch
import torch.nn as nn
from .layers01 import \
PackLayerConv3d, UnpackLayerConv3d, Conv2D, ResidualBlock, InvDepth
from .utils import DepthPredictHead2Up, get_depth_metrics
from mmdet.models import DETECTORS
import torch.nn.functional a... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... |
'''
Copyright: 2016-2019 Thomas Kuestner (thomas.kuestner@med.uni-tuebingen.de) under Apache2 license
@author: Thomas Kuestner
'''
import numpy as np
import tensorflow as tf
import math
from utils.Label import Label
#####################################################################################################... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import time
import unittest
from mock import MagicMock
from bxcommon.utils.expiring_dict import ExpiringDict
from bxcommon.utils.alarm_queue import AlarmQueue
class ExpiringDictTests(unittest.TestCase):
EXPIRATION_TIME_S = 1
def setUp(self):
self.ALARM_QUEUE = AlarmQueue()
self.e_dict = Exp... |
import hashlib
import sys
import getpass
import argparse
import rx7 as rx
from LIB.Functions import pause, cls
from LIB.Hash import sa
def print_hashes(word, file=None, Print=True):
word=bytes(word, encoding='utf-8')
LIST = []
for name,func in sa.items():
try:
result = func(word).he... |
import datetime
import gc
_scope_handler = {
'date': datetime.date,
'datetime': datetime.datetime,
'old_datetime': datetime.datetime,
'old_date': datetime.date}
def set_static_date_time(year=2000, month=7, day=12, hour=9, minute=47, second=40, microsecond=303620):
global _scope_handler
defau... |
"""Implements direct fidelity estimation.
Fidelity between the desired pure state rho and the actual state sigma is
defined as:
F(rho, sigma) = Tr (rho sigma)
It is a unit-less measurement between 0.0 and 1.0. The following two papers
independently described a faster way to estimate its value:
Direct Fidelity Estima... |
#!/usr/bin/env python
# Copyright (c) 2021, Farid Rashidi Mehrabadi All rights reserved.
# ======================================================================================
# Author : Farid Rashidi Mehrabadi (farid.rashidimehrabadi@nih.gov)
# Last Update: Aug 14, 2020
# Description: cleaning
# ==============... |
from .base import AbstractTeam, SimpleTeam, AbstractPlayer
from .base import (SteppingPlayer, SpeakingPlayer,
RoundBasedPlayer, MoveExceptionPlayer, InitialExceptionPlayer,
DebuggablePlayer)
from .team import Team
from .RandomPlayers import RandomPlayer, NQRandomPlayer
from .Foo... |
from gatspy.periodic import LombScargleFast
from scipy import signal
from astropy.stats import LombScargle
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-paper')
import time
"""
comparison between many implementations of lomb-scargle periodogram
"""
# 3 parts separated i... |
#!/usr/bin/python3
import csv
import pandas as pd
import numpy as np
import json
import subprocess
'''
with open('data/final.csv', 'r') as final_csv:
csv_reader = csv.reader(final_csv, delimiter=',')
line_count = 0
for row in csv_reader:
print(row)
'''
data = pd.read_csv('data/final.csv')
sc_balan... |
__version__ = '1.2.1' |
from torch.utils.ffi import _wrap_function
from ._rod_align import lib as _lib, ffi as _ffi
__all__ = []
def _import_symbols(locals):
for symbol in dir(_lib):
fn = getattr(_lib, symbol)
if callable(fn):
locals[symbol] = _wrap_function(fn, _ffi)
else:
locals[symbol] =... |
import crypto
import feed
import binascii
import event
import pcap
import os
class Lora_Feed_Layer:
def __init__(self):
self.verbose = 1
self.callback_sensor_feed = 0
self.callback_control_feed = 0
self.pcap_sensor = 'Sensor_Feed.pcap'
key_sensor = 'keyfile_sensor.key'
... |
# Copyright (c) 2019 UFCG-LSD.
#
# 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,... |
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
from ..SignalProxy import SignalProxy
from .. import functions as fn
from math import log
from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors
from decimal import *
import weakref
__all__ =... |
"""Machine limits for Float32 and Float64 and (long double) if available...
"""
__all__ = ['finfo', 'iinfo']
import warnings
from .machar import MachAr
from .overrides import set_module
from . import numeric
from . import numerictypes as ntypes
from .numeric import array, inf
from .umath import log10, exp2
from . im... |
import time
def dateFormatted(format = '%Y-%m-%d %H:%M:%S'):
datetime = time.localtime()
formatted = time.strftime(format, datetime)
return formatted |
import pdb
import copy
import logging
import itertools
import time
import threading
from multiprocessing import Process
import sklearn.preprocessing
import pytest
from utils import *
from constants import *
uid = "create_collection"
class TestCreateCollection:
"""
********************************************... |
# -*- coding:utf-8 -*-
import sys
from scrapy import cmdline
# dont forget "".split() function
# cmdline.execute("scrapy crawl fb -o ../fb.json".split()) # 默认是当前路径 ../ 是上一级目录
cmdline.execute("scrapy crawl douyumm".split())
# def fib(num):
# a, b, sum = 0, 1, 0
# while sum < num:
# a, b = b, a +... |
from peewee import SqliteDatabase, Model, CharField, IntegerField
db = SqliteDatabase("plusplus.db")
class Plusplus(Model):
name = CharField(primary_key=True) # fields
counter = IntegerField(default=0)
class Meta:
database = db
db.connect()
db.create_tables([Plusplus], safe=True) |
from random import randint
from time import sleep
from operator import itemgetter
jogo = {'Jogador 1': randint(1, 6),
'Jogador 2': randint(1, 6),
'Jogador 3': randint(1, 6),
'Jogador 4': randint(1, 6)}
ranking = list()
print('Valores sorteados: ')
for k, v in jogo.items():
print(f'{k} tirou ... |
import torch as tc
import numpy as np
import copy
import os,sys
import Circle_Function_Class_A0 as ev
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
from torch.optim.lr_scheduler import StepLR
import BasicFunSJR as bfs
from CNNBTN import Paras_VL_CNN_BTN_Collected1chg1
import BasicFun as bf
tm... |
#!/usr/bin/env python
from __future__ import print_function
import argparse, json, os, sys, yaml
parser = argparse.ArgumentParser(description='Keeps project files in sync by converting project.yaml to project.mml.')
parser.add_argument('--check', dest='check', help='write generated JSON to stdout instead to project.m... |
"""Collection of admin utility functions"""
import os
import sys
import logging
from nvp.nvp_component import NVPComponent
from nvp.nvp_context import NVPContext
logger = logging.getLogger(__name__)
# Default .editorconfig content:
DEFAULT_EDITORCONFIG_CONTENT = """# Autogenerated .editorconfig file
# Update as need... |
from manimlib.imports import *
from old_projects.eola.chapter0 import UpcomingSeriesOfVidoes
import random
def plane_wave_homotopy(x, y, z, t):
norm = get_norm([x, y])
tau = interpolate(5, -5, t) + norm/FRAME_X_RADIUS
alpha = sigmoid(tau)
return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z]
... |
# Copyright 2021-xx iiPython
# Modules
import sys
from rich.console import Console
# Logging class
rcon = Console()
class Logging(object):
def __init__(self) -> None:
self._color_map = {"success": "green", "info": "cyan", "warn": "yellow", "error": "red", "crash": "red"}
def log(self, log_type: str, ... |
#
"""Example using weakref.ref to manage a reference to an object.
"""
# end_pymotw_header
import weakref
class ExpensiveObject:
def __del__(self):
print("(Deleting {})".format(self))
obj = ExpensiveObject()
r = weakref.ref(obj)
print("obj:", obj)
print("ref:", r)
print("r():", r())
print("deleting o... |
import re
URL_REGEX = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?... |
from scipy import ndimage
from skimage import measure
import numpy as np
import cv2
def crop_rectangle(image, rect):
# rect has to be upright
num_rows = image.shape[0]
num_cols = image.shape[1]
if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):
print("Proposed rectang... |
# -*- coding: utf-8 -*-
"""flutter_output
Generates graphs, csv's and other files for export of analysis
MORE DETAILS
Typical usage example:
foo = ClassFoo()
bar = foo.FunctionBar()
TODO
- Add spectrogram of changes in modal frequencies at different airspeeds
"""
from mpl_toolkits.mplot3d import Axes3D
imp... |
""""Custom storage for S3."""
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class StaticStorage(S3BotoStorage):
"""Class for static storage."""
location = settings.STATICFILES_LOCATION
class MediaStorage(S3BotoStorage):
"""Class for media storage."""
location... |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
... |
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##... |
from PIL import Image
from PIL import ImageFilter
import os
class ImageLib:
BLUR_LEVEL = 100
EDGE_REMOVAL_FACTOR = 0.08
def __init__(self, path):
abs_path = os.path.abspath(path)
self.img = Image.open(abs_path)
def get_width(self):
return self.img.width
def get_heig... |
import urllib.request
import re,time
s1=time.time()
# some variable for filtering
app_with_download_more_than = 10000
app_updated_after=["year":"2016","date":"1","month":"02"]
def linker(mainlink):
mlink= urllib.request.urlopen(str(mainlink))
page=mlink.read()
#print (page)
link=re.findall('href="/s... |
import sys
def modexp(M, s, n):
'''calculate s**n % M'''
assert n >= 0
assert M > 2
s %= M
def loop(k):
if k == 0:
return 1
elif k == 1:
return s
h = loop(k // 2)
if k % 2 == 0:
return h * h % M
else:
return h ... |
from typing import Tuple
from context import Context
class SimpleFramebuffer:
def __init__(self, size: Tuple[int, int]):
ctx = Context.context
self.image = ctx.image(size, 'rgba8unorm')
self.depth = ctx.image(size, 'depth24plus')
self.framebuffer = [self.image, self.depth]
de... |
import random
import threading
import time
from statistics import mean
from cereal import log
from common.params import Params, put_nonblocking
from common.realtime import sec_since_boot
from selfdrive.hardware import HARDWARE
from selfdrive.swaglog import cloudlog
CAR_VOLTAGE_LOW_PASS_K = 0.091 # LPF gain for 5s tau... |
# 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, software
# distributed under t... |
# %%
import pandas as pd
import librosa
import librosa.display
import os
import numpy as np
import joblib
def scale_minmax(X, min=0.0, max=1.0):
X_std = (X - X.min()) / (X.max() - X.min())
X_scaled = X_std * (max - min) + min
return X_scaled
def gen_melspect(
file_path,
output_name,
sr=None,... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for keeping control who PM's you, Logging pm and muting users in pm """
from telethon.tl.functions.... |
# -*- coding:utf-8 -*-
"""
投资参考类
Created on 2019/01/03
@author: TabQ
@group : gugu
@contact: 16621596@qq.com
"""
from __future__ import division
import math
import time
import pandas as pd
from pandas.compat import StringIO
import lxml.html
from lxml import etree
import re
import json
from gugu.utility import Utility... |
"""
ASGI config for Virtuele project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETT... |
"""
Training without inclusion and exclusion map or train with U-Net model
"""
import csv
import numpy as np
import time
import torch
import os
from argparse import ArgumentParser
from torch.optim import Adam
from torch.utils.data import DataLoader
from src import (
NuClick, UNet, TestDataset, Loss, convert_time... |
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost','badges.dscnitrourkela.tech']
CORS_ORIGIN_WHITELIST =['http://localhost:8080']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} |
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
from guardian.decorators import permission_required
from apps.dashboard.tools import get_base_context, has_access
@login_required
@permission_required('hobbygroups.change_... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def AdminPasswordNotChangedEvent(vim, *args, **kwargs):
'''Default password for the Admin ... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility for checking and processing licensing information in third_party
directories.
Usage: licenses.py <command>
Commands:
... |
import copy
import os
from configobj import ConfigObj
from collections import OrderedDict
class CogctlConfig():
def __init__(self, filename):
self.filename = filename
if os.path.isfile(filename):
# If the file exists it should be valid, so just try to
# get the default pro... |
import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png')
with open('bd_log.png', 'wb') as f:
f.write(r.content) |
"""
This module provides the Scan Op
See scan.py for details on scan
Memory reuse in scan
--------------------
To reduce the number of memory allocations and copies associated with calling
the inner function and recovering the outputs at every iteration, Scan uses a
memory pre-allocation mechanism for some of its o... |
# KLANR ALI @IQTHON
"""Rename Telegram Files
Syntax:
.rnupload file.name"""
import asyncio
import time
from datetime import datetime
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from base64 import b64decode
import io
import math
import os
from pySmartDL import SmartDL
from telet... |
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, 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 requir... |
__author__ = 'Jan Pecinovsky'
from opengrid_dev.config import Config
config = Config()
import os
import sys
import json
import jsonpickle
import datetime as dt
import pandas as pd
from requests.exceptions import HTTPError
import warnings
from tqdm import tqdm
# compatibility with py3
if sys.version_info.major >= 3:... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
class TestROIPooling2D(unittest.TestCase):
def setUp(self):
N = 3
n_channels = 3
self.x = nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.