text stringlengths 1 927k |
|---|
#!/usr/bin/python
# coding=utf-8
'''
redfish-client
This is a client using the python-redfish library to retrieve and perform
action on redfish compatible systems.
'''
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
fr... |
"""Create annotation table
Revision ID: 4c0c44605c09
Revises: 4886d7a14074
Create Date: 2016-01-20 12:58:16.249481
"""
# revision identifiers, used by Alembic.
revision = "4c0c44605c09"
down_revision = "21f87f395e26"
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
from h.d... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# rpi_car_interface_test.py
# Created: 2017.11.10
# Uvindu Wijesinghe and Oliver Wilkins
#
# Description:
# This program sets up a serial port and allows the Raspberry Pi to
# send data to the Arduino that is connected to the USB port.
# This can be used to control the driving speed and steering input
# of the car
#
... |
"""Matplotlib based plotting of quantum circuits.
Todo:
* Optimize printing of large circuits.
* Get this to work with single gates.
* Do a better job checking the form of circuits to make sure it is a Mul of
Gates.
* Get multi-target gates plotting.
* Get initial and final states to plot.
* Get measurements to plo... |
# Copyright (C) 2016 Nippon Telegraph and Telephone 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 appli... |
from math import sqrt
from pygeom.matrix3d import zero_matrix_vector
from matplotlib.pyplot import figure
from .latticesheet import LatticeSheet
from .latticepanel import LatticePanel
class LatticeSurface(object):
name = None
scts = None
shts = None
cspc = None
xspace = None
strps = None
pn... |
"""
Comparison of a UW model with a GC analysis
$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like2/analyze/gc_comparison.py,v 1.3 2017/11/17 22:43:17 burnett Exp $
"""
import os
from astropy.io import fits as pyfits
import numpy as np
import pylab as plt
import pandas as pd
from astropy.io import fits
f... |
from datetime import datetime
def current_datetime(request):
return dict(current_datetime=datetime.now()) |
from amadeus.client.decorator import Decorator
class BySquare(Decorator, object):
def get(self, **params):
'''
Returns detailed safety ranking of all the districts
within the designated area.
.. code-block:: python
amadeus.safety.safety_rated_locations.by_square.g... |
import logging
class SensorFilter(logging.Filter):
"""
Filters out records starting with the level "sensorlog"
"""
def filter(self, record):
return not record.name.startswith("sensorlog") |
from ..utils import rest
from ..utils.checks import check_datetime, check_date
from ..utils.resource import Resource
class UtilityPayment(Resource):
"""# UtilityPayment object
When you initialize a UtilityPayment, the entity will not be automatically
created in the Stark Bank API. The 'create' function se... |
import sqlalchemy as sa
from sqlalchemy.test import testing
from sqlalchemy import Integer, String, ForeignKey
from sqlalchemy.test.schema import Table
from sqlalchemy.test.schema import Column
from sqlalchemy.orm import mapper, relation, create_session
from test.orm import _base
class LazyTest(_base.MappedTest):
... |
# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# 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... |
# 간단 환율계산 (달러)
from datetime import *
clock = datetime.now()
ymd = "%s 년 %s 월 %s 일"%(clock.year, clock.month, clock.day)
_usd_ = 1126.97
def Conversion(v, c):
return v * c # 환율
print("-- 간단 환율 계산 (달러) --")
print("-> 환율: %s 기준 -<"%ymd)
while True:
value = float(input("달러(0:quit): "))
if value == 0.0:
... |
#!/usr/bin/env python
# Full license can be found in License.md
# Full author list can be found in .zenodo.json file
# DOI:10.5281/zenodo.1199703
# ----------------------------------------------------------------------------
import copy
import datetime as dt
from functools import partial
import numpy as np
import os
i... |
import sys, os, collections, copy
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
data_fn = 'data/WikiQA-train.tsv'
X = pd.read_csv(data_fn, sep='\t', header=0, dtype=str, skiprows=None, na_values='?', keep_default_na=False) |
# This is a simple calculator in the shell
def use(num1, t, num2):
try:
num1 = float(num1)
num2 = float(num2)
if t == '+':
a = num1 + num2
q = '{} + {}'.format(num1, num2)
elif t == '-':
a = num1 - num2
q = '{} - {}'.format(num1, num2)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Contrast Variation Resonant Soft X-ray Scattering documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 28 12:35:56 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible con... |
from unittest import TestCase
from unittest.mock import MagicMock, Mock, patch
from splunk_connect_for_snmp.customtaskmanager import CustomPeriodicTaskManager
class TestCustomTaskManager(TestCase):
@patch("celerybeatmongo.models.PeriodicTask.objects")
def test_delete_unused_poll_tasks(self, m_objects):
... |
import re
import sys
import csv
import xlrd
from copy import copy
INPUT_FILE = "/Users/tomaszkolek/Downloads/buffalo.xls"
# INPUT_FILE = "/Users/tomaszkolek/Downloads/Nelson Bay.xls"
OUTPUT_BILLS = "bill.csv"
OUTPUT_INCREASE = "increase.csv"
IGNORE_COLUMN = ["Budget Year 2019/20 % incr"]
IGNORE_ROW = ["sub-total"]
C... |
# Re-export of Bazel rules with repository-wide defaults
load("@angular//:index.bzl", _ng_module = "ng_module")
load("@build_bazel_rules_nodejs//:defs.bzl", _jasmine_node_test = "jasmine_node_test")
load("@build_bazel_rules_typescript//:defs.bzl", _ts_library = "ts_library",
_ts_web_test_suite = "ts_web_test_suite")... |
"""This module contains the general information for VnicEtherIf ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class VnicEtherIfConsts():
ADDR_DERIVED = "derived"
DEFAULT_NET_FAL... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import pdb
from tensorflow.contrib import legacy_seq2seq
from lib.metrics import masked_mae_loss
from model.dcrnn_cell import DCGRUCell
class DCRNNARModel(object):
def __init__(s... |
# Copyright (C) 2015 Yahoo! 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... |
import calendar
import unittest
from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure
import time
import locale
import sys
import datetime
import os
# From https://en.wikipedia.org/wiki/Leap_year_starting_on_Saturday
result_0_02_text = """\
February 0
Mo Tu We Th... |
r"""
Hyperplanes
.. NOTE::
If you want to learn about Sage's hyperplane arrangements then you
should start with
:mod:`sage.geometry.hyperplane_arrangement.arrangement`. This
module is used to represent the individual hyperplanes, but you
should never construct the classes from this module directly... |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google 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 requir... |
#!/usr/bin/env python3
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.feat1 = nn.Sequential(nn.Flatten(), nn.Linear(50*5*5, 32*5*5), nn.ReLU())
self.feat2 = nn.Sequential(nn.Linear(32*5*5, 32*12), nn.ReLU())
self.linear = nn.Se... |
# coding=utf-8
import xlrd
# 打开文件
data = xlrd.open_workbook('file/demo.xlsx')
# 查看工作表
data.sheet_names()
print("sheets:" + str(data.sheet_names()))
# 通过文件名获得工作表,获取工作表1
table = data.sheet_by_name('工作表1')
# 获取某个单元格的值,例如获取B3单元格值
cel_B3 = table.cell(3,2).value
print("第三行第二列的值:" + cel_B3)
#D列+5
cel_D2=table.cell(1,3).... |
from django.core.files.storage import Storage
from django.conf import settings
class FastDFSStorage(Storage):
"""自定义文件存储系统,修改存储的方案"""
def __init__(self, fdfs_base_url=None):
"""
构造方法,可以不带参数,也可以携带参数
:param base_url: 存储服务器的位置
"""
self.fdfs_base_url = fdfs_base_url or set... |
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, My fun. You're at the Test index.") |
class Solution(object):
@staticmethod
def longest_palindromic(s: str):
# Square Matrix - length = length of the string [False]
matrix = [[False for i in range(len(s))] for i in range(len(s))]
for i in range(len(s)):
# major diagonal elements = True
matrix[i][... |
import os
import pytest
import torch
import torch.distributed as dist
import ignite.distributed as idist
from ignite.distributed.utils import has_native_dist_support
from tests.ignite.distributed.utils import (
_test_distrib_all_gather,
_test_distrib_all_reduce,
_test_distrib_barrier,
_test_distrib_br... |
# Copyright 2013 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.
"""Code shared by the various language-specific code generators."""
from functools import partial
import os.path
import re
import module as mojom
import mo... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators impo... |
# -*- coding: utf-8 -*-
"""
Unit tests for the dialect detection.
Author: Gertjan van den Burg
"""
import unittest
from clevercsv.detect import Detector
class DetectorTestCase(unittest.TestCase):
# Initially we copy the results from CPython test suite.
sample1 = """\
Harry's, Arlington Heights, IL, 2/1/... |
# class A:
# def sum(self):
# print("A")
# class B:
# def sum(self):
# print("B")
# class C(B,A):
# pass
# o = C()
# o.sum()
# n =12345
# sum =0
# temp = n
# num = n %10
# rev = rev*10+num
# digit = n//10
# if temp== rev:
# this is palindrome
# else:
# this is not palindrome
... |
import datetime
import os.path
import unittest
here = os.path.dirname(__file__)
# 5 years from now (more or less)
fiveyrsfuture = datetime.datetime.utcnow() + datetime.timedelta(5*365)
class Test_static_view_use_subpath_False(unittest.TestCase):
def _getTargetClass(self):
from pyramid.static import stati... |
# 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
# d... |
# 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 argparse
import json
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from venv import EnvBuilder
cl... |
from flask import Flask ,request
from flask_restful import Resource, Api
import requests
app =Flask(__name__)
api = Api(app)
#cluster = {'metric': {'name':"slurm_nodes_idle" ,'instance':"35.209.219.226:8080",'job':"slurm2"},
# 'value':{0:1593766788.942, '1':"3"}}
#resp = requests.get('http://15.206.250.89:9... |
# 对列表中的字典按照某一个key值进行排序
# 对于每个对象有不同属性,多个对象组成一个组合的情况,可以适用
students = [
{'name':'Tom', 'age':18},
{'name':'Rose', 'age':16},
{'name':'Jack', 'age':17}
]
# 按name值升序排序
students1 = students.copy()
students1.sort(key=lambda x: x['name'])
print(students1)
# 按name值降序排序
students2 = students.copy()
students2.sort(k... |
# Generated by Django 3.0.4 on 2020-05-25 10:01
from django.conf import settings
import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = Tr... |
import asyncio
from typing import Any, Dict, Text, List, Callable, Optional
from unittest.mock import Mock
import pytest
from _pytest.logging import LogCaptureFixture
from _pytest.monkeypatch import MonkeyPatch
from pytest_sanic.utils import TestClient
from sanic import Sanic, response
from sanic.request import Reques... |
import torch
from .. import settings
def _default_preconditioner(x):
return x.clone()
def linear_cg(matmul_closure, rhs, n_tridiag=0, tolerance=1e-6, eps=1e-20, max_iter=None,
initial_guess=None, preconditioner=None):
"""
Implements the linear conjugate gradients method for (approximately)... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class FoodSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy act... |
import nao_nocv_2_1 as nao
from naoqi import ALProxy
def InitRobot():
nao.InitProxy("192.168.0.117")
# local = 127.0.0.1
# marvin = 192.168.0.115
# bender = 192.168.0.117
robotIP= "192.168.0.117"
def basicWave():
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.... |
import gdb
# these definitions and tagof must be in sync with C source
class Tag:
unknown = 0
string = 1
symbol = 2
table_tuple = 3
function_tuple = 4
def tagof(p):
return ((p.cast(typ('u64')) >> 38) & 7)
def typ(s):
return gdb.lookup_type(s)
def get_buffer_string(val):
str = val['co... |
# by Kami Bigdely
# Docstrings and blank lines
class OnBoardTemperatureSensor:
VOLTAGE_TO_TEMP_FACTOR = 5.6
def __init__(self):
pass
def read_voltage(self):
return 2.7
def get_temperature(self):
return self.read_voltage() * OnBoardTemperatureSensor.VOLTAGE_TO_TEMP_FACTOR ... |
# Generated by Django 3.2.12 on 2022-03-13 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0006_auto_20220313_1339'),
]
operations = [
migrations.AddField(
model_name='user',
name='created_at',
... |
from {{cookiecutter.repo_name}}.settings.base import *
DEBUG = True
# CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# END CACHE CONFIGURATION
# DATABASE CONFIGURATION
# See:... |
from django.db import models
class ComplementAttraction(models.Model):
name = models.CharField(max_length=150)
description = models.TextField()
opening_hours = models.TextField()
image = models.ImageField(upload_to='attractions', null=True, blank=True)
def __str__(self):
return self.name |
# Copyright (c) 2016 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.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
# -*- coding: utf-8 -*-
'''
Set up the version of Salt
'''
# Import python libs
from __future__ import print_function
import re
import sys
# Import salt libs
try:
from salt._compat import string_types
except ImportError:
if sys.version_info[0] == 3:
string_types = str
else:
string_types = ... |
# 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, overload
from ... import _utilities
fro... |
# -*- coding: utf-8 -*-
# Copyright 2022 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 applicable law or... |
from .input import (
import_builtin_asset,
mesh_paths,
import_landmark_file,
import_landmark_files,
data_path_to,
data_dir_path,
ls_builtin_assets,
landmark_file_paths,
import_mesh,
import_meshes,
register_landmark_importer,
register_mesh_importer,
import_lsfm_model,
... |
# 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, overload
from ... import _utilities
fro... |
import os
import glob
from .env import IS_WINDOWS, IS_DARWIN, IS_CONDA, CONDA_DIR, check_negative_env_flag, \
gather_paths
from .cuda import USE_CUDA, CUDA_HOME
USE_NCCL = USE_CUDA and not check_negative_env_flag('USE_NCCL') and not IS_DARWIN and not IS_WINDOWS
USE_SYSTEM_NCCL = False
NCCL_LIB_DIR = None
NCCL_SY... |
# Copyright 2011 OpenStack LLC.
from cinderclient import base
class Limits(base.Resource):
"""A collection of RateLimit and AbsoluteLimit objects."""
def __repr__(self):
return "<Limits>"
@property
def absolute(self):
for (name, value) in list(self._info['absolute'].items()):
... |
import os
import option
import grapeGit as git
import utility
import grapeConfig
class Push(option.Option):
"""
grape push pushes your current branch to origin for your outer level repo and all submodules.
it uses 'git push -u origin HEAD' for the git command.
Usage: grape-push [--noRecurse]
Op... |
# 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 may ... |
import requests
import re
import os
import json
import datetime
import json5
from io import StringIO
from nameparser import HumanName
from bibtex import BibTeX # use local patched version instead of citeproc.source.bibtex
import urllib2
import urlparse
import re
from arxiv2bib import arxiv2bib_dict, is_valid
from uti... |
# Import packages
import pandas as pd
from datetime import datetime
import numpy as np
#Reading predicted data and changing date column data type
pdata = pd.read_csv('/home/pi/LABS/Asingment/Real-time-Edge-analytics/PredictionDataset.csv', skiprows=0)
pdata['Date'] = pd.to_datetime(pdata['Date'])
#Selecting data acco... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label":_("Dealer"),
"icon": "octicon octicon-briefcase",
"items": [
{
"type": "doctype",
"name": "Venta de Auto",
"label": _("Venta de Auto"),... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. Team and deepset Team.
# Copyright (c) 2018, 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 m... |
# Copyright 2020 TestProject (https://testproject.io)
#
# 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 ... |
# coding: utf-8
import nose
import itertools
import string
from distutils.version import LooseVersion
from pandas import Series, DataFrame, MultiIndex
from pandas.compat import range, lzip
import pandas.util.testing as tm
from pandas.util.testing import slow
import numpy as np
from numpy import random
from numpy.ran... |
#!/usr/bin/env python3
# Ukljucivanje modula za matematiku
import numpy as np
import numpy.linalg as LA
# Ukljucivanje modula za upozorenja
import warnings
# NAPOMENA: svi razmatrani uglovi zadati su u radijanima,
# sto je u skladu sa uobicajenom informatickom praksom
# Matrica rotacije koja odgovara sopstvenim rot... |
import os, sys, subprocess
default_dir = os.path.join(os.path.expanduser('~'), 'Videos/')
if not os.path.exists(default_dir + "test"):
os.mkdir(default_dir + "test")
else:
print("path exists\n " + default_dir + "test")
if not os.path.exists(default_dir + "test/pics"):
os.mkdir(default_dir + "test/pi... |
class Solution:
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
i, j = 0, len(matrix[0]) - 1
while i < len(matrix) and j >= 0 :
if matrix[i][j] == target:
return True
elif matrix[i][j] > ta... |
# date: 2021.07.14
# author: Raul Saavedra raul.saavedra.felipe@iais.fraunhofer.de
import grpc
from concurrent import futures
import time
import numpy
# import constant with the hardcoded openml data ID number
import myconstants
# import the generated grpc related classes for python
import model_pb2
import model_pb2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# s3qlite documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# aut... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2019, Battelle Memorial Institute.
#
# 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... |
import importlib
from models.base_model import BaseModel
def find_model_using_name(model_name):
# Given the option --model [modelname],
# the file "models/modelname_model.py"
# will be imported.
model_filename = "models." + model_name + "_model"
modellib = importlib.import_module(model_filename)
... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import sys
import timeit
from typing import List, Optional, Tuple
class Board:
def __init__(self, board: Tuple[int]):
self._board = board
self._marks = [False] * 5 * 5
self._number = None
def play(self, number: int) -> None:
if... |
# Copyright (C) 2001-2007 Python Software Foundation
# Author: Barry Warsaw, Thomas Wouters, Anthony Baxter
# Contact: email-sig@python.org
"""A parser of RFC 2822 and MIME email messages."""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
__all__ = ["Par... |
import json
import os
import random
import numpy as np
import time
import redis
import msgpack
def read_data(filename='dict/parsed_wiki_fr2sp.json'):
db = redis.Redis(host='redis')
pack = db.get(filename)
if pack is not None:
return msgpack.unpackb(pack)
with open(filename, 'r') as f:
... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2021-2022 Valory AG
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
import curses
import sys
import threading
import re
import argparse
import os
import io
import ctypes
import tempfile
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import castero
from castero import helpers
from castero.config import Config
from castero.database import Database
from castero.d... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
r"""
The pyro.infer.autoguide.initialization module contains initialization functions for
automatic guides.
The standard interface for initialization is a function that inputs a Pyro
trace ``site`` dict and returns an appropriatel... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import KazuByteTestFramework
from test_framework.util import *
class... |
# coding: UTF-8
"""
工具类
https://github.com/jhao104/proxy_pool
在使用前需配置好上面的代理ip池
并需要购买"高匿代理"以进行不间断爬取
"""
import requests
from lxml import etree
import random
from requests.exceptions import Timeout, RequestException
import time
# import chardet
user_agent_list = [
'Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Tride... |
from typing import Match
import cv2 as cv
import numpy as np
from numpy.core.fromnumeric import ndim
'''
In this module, i will implement motion tracking with contour detection and contour drawing.
'''
def histOfObjects(objects = []) :
'''
Calculate the histograms of input objects.
'''
objHists = []
... |
from aimacode.planning import Action
from aimacode.search import Problem
from aimacode.utils import expr
from lp_utils import decode_state
class PgNode():
"""Base class for planning graph nodes.
includes instance sets common to both types of nodes used in a planning graph
parents: the set of nodes in the ... |
passwordFile = open('secret_pass.txt')
secretPassword = passwordFile.readline().strip()
print('Secret pass is:', secretPassword)
print('Enter your password')
typedPassword = input()
if typedPassword == secretPassword:
print('Access granted')
if typedPassword == '12345':
print('That password is one that... |
import scipy
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
l = scipy.misc.ascent()
l = l[230:290, 220:320]
noisy = l + 0.4 * l.std() * np.random.random(l.shape)
gauss_denoised = ndimage.gaussian_filter(noisy, 2)
plt.subplot(121)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
pl... |
import os
import time
DAYS = 5 # Maximal age of file to stay, older will be deleted
FOLDERS = [
"G:\Musorka\HLAM"
]
TOTAL_DELETED_SIZE = 0 # Total deleted size of all files
TOTAL_DELETED_FILE = 0 # Total deleted files
TOTAL_DELETED_DIRS = 0 # Total deleted empty folders
#===========... |
from .AccidentData import AccidentData
class FullAccidentData(AccidentData):
"""Clase que describe los datos entregados por el cliente sobre accidentes viales"""
def __init__(self, information):
super().__init__()
self.client = information.client
self.client_name = information.client_... |
"""Utility functions"""
import json
import os
import datetime
import logging
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
def load_config_json(name):
json_path = os.path.abspath(os.path.join(BASE_DIR, 'microservice')) + '/' + name + '.json'
... |
"""
Base Test Case.
"""
import os
import tempfile
import shutil
from unittest import TestCase as BaseTestCase
from cfg.main_cfg import CFG
class TestCase(BaseTestCase):
cfg = CFG()
EXAMPLES_PATH = './test/examples'
""" Test Case Methods """
@classmethod
def setUpClass(cls):
cls.cfg.OUTP... |
import re
import ftfy
import json
import spacy
from tqdm import tqdm
def get_pairs(word):
"""
Return set of symbol pairs in a word.
word is represented as tuple of symbols (symbols being variable-length strings)
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add... |
# BSD 3-Clause License
#
# Copyright (c) 2019, FPAI
# Copyright (c) 2019, SeriouslyHAO
# Copyright (c) 2019, xcj2019
# Copyright (c) 2019, Leonfirst
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are... |
from imutils import face_utils
import numpy as np
import argparse
import imutils
import dlib
import cv2
import copy
import colorsys
import math
import os
import shutil
import collections
from convexHull import convexHull, convexRectangle
from processBar import progressbar
from genTeethColor import findTeethColor, rea... |
# coding: utf-8
from __future__ import unicode_literals
import inspect
import pickle
import re
import unittest
from collections import Mapping
import pytest
from django.db import models
from rest_framework import fields, relations, serializers
from rest_framework.compat import unicode_repr
from rest_framework.fields... |
import json
import random
import requests
# url = 'https://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=&start=0&limit=491'
# headers = {
# 'User-Agent': 'jdskajdjjkjvd',
# }
# data_list = requests.get(url, headers=headers).json()
# with open('douban.txt', mode='a+', encoding='utf-8') a... |
#!/usr/bin/env python
"""
Vagrant external inventory script. Automatically finds the IP of the configured
vagrant vm(s), and returns it under the host group 'vagrant'
Example Vagrant configuration using this script:
config.vm.provision :ansible do |ansible|
ansible.playbook = "./provision/your_playbook.yml"... |
from pathlib import Path
import pickle
import warnings
import numpy as np
import pandas as pd
from pandas.core.common import SettingWithCopyWarning
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitor
from pytorch_lightning.loggers import TensorBoardLogger
import to... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.config import cfg
from model.test import im_detect
from model.nms_wrapper import nms
from utils.timer import Timer
import matplotlib.pyplot as plt
import numpy as np
import os, cv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.