text stringlengths 2 999k |
|---|
POST = 'POST'
GET = 'GET'
|
## Install modules sqlparse and pyyaml for this pkg to work
import os
import sqlparse
import yaml
import pandas as pd
from yaml.loader import SafeLoader
def ParseSql(filePath):
#filePath = "/Volumes/MyDrive/src/main/resources/sql/hl/hl_ongoing.sql"
if os.path.exists(filePath):
# filename = os.pa... |
# coding=utf-8
from base.APIConstants import Constants
from base.APISenderBase import Base
import logging
__REG_ID_SPLITTER__ = ","
class APITools(Base):
"""
API工具(查询消息状态, 统计, 删除定时任务等)
构造方法接收一个参数:
@:param security 必须 - APP_SECRET
"""
def check_schedule_job_exist(self, job_id, retry_times=1):... |
import psycopg2
import logging
import sys
logger = logging.getLogger(__name__)
class DbaseException(Exception):
pass
class SelectorPostgreSQL:
def __init__(self, device, db_setting):
self.cursor = None
self.device = device
self.connection = psycopg2.connect(host=db_setting['server']... |
import datetime
import re
import secrets
import time
from datetime import timedelta
from typing import (
AbstractSet,
Any,
Callable,
Dict,
List,
Optional,
Pattern,
Sequence,
Set,
Tuple,
TypedDict,
TypeVar,
Union,
)
from uuid import UUID, uuid4
import django.contrib.a... |
#!/usr/bin/env python
# --------------------------------------------------------
# R-FCN
# Copyright (c) 2016 Yuwen Xiong
# Licensed under The MIT License [see LICENSE for details]
# Written by Yuwen Xiong
# --------------------------------------------------------
"""
Demo script showing detections in sample images.
... |
#先爬取所有城市以及对应城市的空气质量指标,然后做一个top50的图表
#http://pm25.in/rank
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 处理- 显示问题
r = requests.get('http://pm25.in/rank')
soup = BeautifulSoup(r.... |
import json
import logging
from django import forms
from django.contrib import messages
from django.core.validators import validate_email
from django.utils.translation import ugettext_lazy as _
from .models import EmailTemplate, EmailTemplateQuerySet
logger = logging.getLogger(__name__)
class JSONWidget(forms.Text... |
from signal import pause
from pitop import Camera, DriveController, Pitop
from pitop.processing.algorithms.line_detect import process_frame_for_line
# Assemble a robot
robot = Pitop()
robot.add_component(DriveController(left_motor_port="M3", right_motor_port="M0"))
robot.add_component(Camera())
# Set up logic based... |
#!/usr/bin/env python
import os
import sys
import string
import time
import datetime
import traceback
import MySQLdb
import pymssql
import logging
import logging.config
logging.config.fileConfig("etc/logger.ini")
logger = logging.getLogger("clean_history")
path='./include'
sys.path.insert(0,path)
import functions as fu... |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... |
import os.path
import pytest
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.test import taddons
from mitmproxy import io
from mitmproxy import exceptions
from mitmproxy.tools import dump
from mitmproxy.addons import streamfile
def test_configure():
sa = streamfile.StreamFile()... |
"""Test cases for the wikipedia module."""
from unittest.mock import Mock
import click
import pytest
from hypermodern_pitron import wikipedia
def test_random_page_uses_given_language(mock_requests_get: Mock) -> None:
"""It selects the specified Wikipedia language edition."""
wikipedia.random_page(language=... |
from functools import wraps
from botocore.paginate import TokenDecoder, TokenEncoder
from functools import reduce
from .exceptions import InvalidToken
PAGINATION_MODEL = {
"list_executions": {
"input_token": "next_token",
"limit_key": "max_results",
"limit_default": 100,
"page_end... |
class Solution(object):
def searchRange(self, nums, target):
l, r = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target) - 1
return [l, r] if 0 <= l <= r else [-1, -1] |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2021 CERN.
# Copyright (C) 2020-2021 Northwestern University.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Invenio Resources module to create REST API... |
from box import Box, BoxList
from restfly import APISession
from restfly.endpoint import APIEndpoint
from pyzscaler.utils import Iterator
class SAMLAttributesAPI(APIEndpoint):
def __init__(self, api: APISession):
super().__init__(api)
self.v2_url = api.v2_url
def list_attributes(self, **kwa... |
#!/usr/bin/env python3
"""Module containing the KMeansCoefficient class and the command line interface."""
import argparse
from biobb_common.generic.biobb_object import BiobbObject
from sklearn.preprocessing import StandardScaler
from biobb_common.configuration import settings
from biobb_common.tools import file_util... |
# -*- coding: utf-8 -*-
#
# Cipher/Salsa20.py : Salsa20 stream cipher (http://cr.yp.to/snuffle.html)
#
# Contributed by Fabrizio Tarizzo <fabrizio@fabriziotarizzo.org>.
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the exten... |
from __future__ import print_function, division
from sympy.sets import FiniteSet
from sympy import (sqrt, log, exp, FallingFactorial, Rational, Eq, Dummy,
piecewise_fold, solveset, Integral)
from .rv import (probability, expectation, density, where, given, pspace, cdf, PSpace,
character... |
#© 2017-2020, ETH Zurich, D-INFK, lubu@inf.ethz.ch
import sys
import time
from threading import Thread
import virtualchain
from config import *
from talosvc.policydb import TalosPolicyDB
"""
Implementation of the blockstack virtualchain library hooks.
The updates are feeded to our state machine implementation.
"""
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... |
import sys
#pylint: disable=E0611
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel, QPushButton, QMainWindow
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
centerWidget = QWidget... |
_base_ = [
'../../lvis/mask_rcnn_r50_fpn_sample1e-3_mstrain_2x_lvis_v1.py'
]
# data = dict(train=dict(oversample_thr=0.0))
model = dict(roi_head=dict(bbox_head=dict(loss_cls=dict(type="IIFLoss",variant='raw'),
init_cfg = dict(type='Constant',val=0.001, bias=0.0, override=d... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import subprocess
import json
import os.path
import sys
import numpy
def main():
program = os.path.realpath("coarsemc")
#inputdir = os.path.join("tests",
# "zero_sweeps")
inputdir = ""
ntasks = 1
energies = collect_energies(nt... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from knowit.rules import AudioChannelsRule
from . import (
assert_expected,
parameters_from_yaml,
)
@pytest.fixture
def audiochannels_rule():
return AudioChannelsRule('audio channels')
@pytest.mark.parametrize('expected,inpu... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
def manage_updaters(request):
"Представление: управление загрузчиками."
from catalog.models import Updater
if request.user.has_perm('catalog.add_updater')\
or request.user.has_p... |
import threading
import spotipy
import spotipy.util as util
from Models.ModelAPI import API
class SpotifyApi(API):
def __init__(self):
super(SpotifyApi, self).__init__()
self.data = self.OpenAPIData()
self.data = self.data["spotify"]
try:
self.client_id = self.data["c... |
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QGraphicsPixmapItem
from client.constants import IMAGES_DIR
class Barrel(QObject):
draw_signal = pyqtSignal()
remove_signal = pyqtSignal()
fall_signal = pyqtSignal()
def __init__(self, parent, ind... |
"""
This module contains classes that can be used for the implementation of
bolt tasks.
"""
import logging
class Task(object):
"""
"""
def __call__(self, **kwargs):
self.config = kwargs.get('config')
self._configure()
self._execute()
def _configure(self):
"""
... |
import sys
import csv
import glob
import os
import pandas as pd
import collections
import traceback
from os.path import basename, dirname
from pkg_resources import resource_filename
import argparse
#from PyQt5.QtCore import *
#from PyQt5.QtGui import QFileDialog
#from PyQt5 import QtWidgets
from PyQt5.QtWidgets import... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: setting.py
Description : 配置文件
Author : JHao
date: 2019/2/15
-------------------------------------------------
Change Activity:
2019/2/15:
-------------------------------------... |
import numpy as np
import os
import sys
import ntpath
import time
from . import util, html
from subprocess import Popen, PIPE
if sys.version_info[0] == 2:
VisdomExceptionBase = Exception
else:
VisdomExceptionBase = ConnectionError
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256, it... |
from .server import blocking_handler_wrapper, load_settings, server, time_measurement, time_measurement_async
|
# 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... |
callback_classes = [
['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Mac48Address', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],... |
class Node:
def __init__(self, value, children, count, terminate):
self.value = value
self.children = children
self.count = count
self.terminate = terminate
def terminate(self):
self.terminate = True
def count(self):
self.count += 1
d... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# midi_inoutdemo - demonstrates receiving and sending MIDI events
import usb_midi
import adafruit_midi
# TimingClock is worth importing first if present as it
# will make parsing more efficient for this high frequency event... |
import requests
#设计父类 各个用例类继承父类
class BaseApi(object):
#设置通用变量
method = "GET"
url = ""
params = {}
headers = {}
cookies = {}
data = {}
json = {}
def __init__(self):
self.response = None
#初始化各请求参数
def set_params(self, **params):
self.params = params
return se... |
# Generated by Django 2.2.10 on 2020-03-25 19:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0006_activationcode'),
]
operations = [
migrations.AlterField(... |
FPS = 60
WIDTH = 8
HEIGHT = 9
TILE_LENGTH = 70
TILES = WIDTH*HEIGHT |
#!/usr/bin/python
# -*- coding: utf8 -*-
# Copyright 2017 Per Grön. 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
#
... |
"""
Copyright (c) 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from textwrap import dedent
import json
import logging
import requests
import time
from atomic_reactor.constants import REMOTE_SOURCE_TARBAL... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
import numpy as np
import torch
import random
from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree
from utils import evaluate_actions_sil
# replay buffer...
class ReplayBuffer:
def __init__(self, size):
self._storage = []
self._maxsize = size
self._next_idx = 0
def ... |
# 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.
# pyre-strict
import re
from abc import ABC, abstractmethod
from ast import literal_eval
from contextlib import contextmanager
from dataclass... |
# https://leetcode.com/problems/score-of-parentheses/description/
#
# algorithms
# Medium (55.2%)
# Total Accepted: 4.7K
# Total Submissions: 8.5K
# beats 100.0% of python submissions
from collections import deque
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
... |
from os import system
def make_gif(files, output, delay=100, repeat=True, **kwargs):
"""
Uses imageMagick to produce an animated .gif from a list of
picture files.
"""
loop = -1 if repeat else 0
system('convert -delay %d -loop %d %s %s'
%(delay, loop, " ".join(files), output))
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Python Word Sense Disambiguation (pyWSD): Misc utility functions
# Copyright (C) 2014-2018 alvations
# For license information, see LICENSE.md
from nltk.corpus import wordnet as wn
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk import pos_tag
import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Open Referral documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 2 14:17:45 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in thi... |
"""Test Wallbox Init Component."""
import json
import requests_mock
from homeassistant.components.wallbox import CONF_MAX_CHARGING_CURRENT_KEY
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import test_response
from tests.components.wallbox import (
... |
import cv2
import numpy as np
import color
import centroid
from directkeys import PressKey, W, A, S, D
cap = cv2.VideoCapture(2)
fps = cap.get(cv2.CAP_PROP_FPS)
print ("Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps))
while True:
_, frame = cap.read()
frame = cv2.resize(frame, (600, 4... |
"""
Mixins to be inherited by AbstractEvent
They are split up in order make them easier to read,
and because there was (once upon a time) an idea to split up the information
about an event and the registration info into different models.
"""
from datetime import datetime
from django.db import models
from six.moves.u... |
# Copyright 2017 yanyan. 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... |
from django.conf.urls import url
from product import views
urlpatterns = [
url(r'sale/(?P<invoice_id>\d+)/$', views.sale, name='product_sale'),
url(r'invoicelist/$', views.InvoiceListView.as_view(),
name='invoice_list'),
url(r'invoice/$', views.invoice, name='product_invoice'),
url(r'invoiced... |
import logging
import report_generator.io.yaml as report_generatoryaml
logger = logging.getLogger("report_generator")
# resource_package = __name__
# resource_path_packages = '/'.join(('../data', 'packages.yaml'))
# resource_path_sponsors = '/'.join(('../data', 'sponsors.yaml'))
#
# template_packages = pkg_resource... |
# -*- coding: utf-8 -*-
"""User models."""
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlencode
import re
import hashlib
import datetime as dt
from time import mktime
import pytz
from flask_login import UserMixin
from flask import current_app
from dribdat.extensio... |
import turtle
t = turtle.Turtle()
t.left(90)
t.backward(133)
t.color("green")
t.speed(108)
t.clone()
perc = 0.7
angle = 33.0
shortest = 10
def fract(n):
if n >= shortest:
t.forward(n)
t.right(angle)
fract(n * perc * 0.8)
t.left(angle)
fract(n * perc)
t.left(angle)... |
# Copyright 2017 gRPC 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 in writing... |
import torch
import torch.nn as nn
import os
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm as pbar
import numpy as np
import time
from tqdm import tqdm
import scipy.linalg
import random
from random import shuffle
is_print = True
def _print(*args, **kwargs):
if is_print:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017 Futu, 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 requi... |
from typing import List
from zulint.custom_rules import Rule, RuleList
# Rule help:
# By default, a rule applies to all files within the extension for which it is specified (e.g. all .py files)
# There are three operators we can use to manually include or exclude files from linting for a rule:
# 'exclude': 'set([<pat... |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# 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 witho... |
# Cloud Automation Services SDK for Python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class Deployment(object):
"""
Classes for Cloud Zone methods.
"""
def __init__(self,
deployment):
self.id = deployment['id']
self.na... |
import numpy as np
import pandas as pd
import tensorflow as tf
from pathlib import Path
import joblib
from tensorflow.keras import models
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from custom_utils import DateTransformer, create_integer_scores
def load_a_... |
#!/usr/bin/env python
#
# (C) 2001 by Argonne National Laboratory.
# See COPYRIGHT in top-level directory.
#
import sys, os, socket
manPort = int(sys.argv[1])
manSock = socket.socket()
manSock.connect((socket.gethostname(),manPort))
msg = manSock.recv(3) # 'go\n'
if not msg.startswith('go'):
print 'mps... |
import os
from pathlib import Path
import numpy as np
import pytest
from jina import Executor
from jina.excepts import BadFlowYAMLVersion
from jina import Flow
from jina.jaml import JAML
from jina.jaml.parsers import get_supported_versions
from jina.parsers.flow import set_flow_parser
from jina.types.document.generat... |
# coding: utf-8
"""Tests for profile-related functions.
Currently only the startup-dir functionality is tested, but more tests should
be added for:
* ipython profile create
* ipython profile list
* ipython profile create --parallel
* security dir permissions
Authors
-------
* MinRK
"""
from __futur... |
"""Tests for the metrics module."""
import numpy as np
import unittest
from lpot.metric import METRICS
from lpot.experimental.metric.f1 import evaluate
from lpot.experimental.metric import bleu
class TestMetrics(unittest.TestCase):
def testmIOU(self):
metrics = METRICS('tensorflow')
miou = metrics[... |
import os
import json
from web3 import Web3
import discord
from discord.ext import commands, tasks
BOT_TOKEN = os.environ["DISCORD_BOT_TOKEN"]
# Initialized Discord client
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(intents=intents, help_command=None, command_prefix='&?')
# Initializ... |
# -*- coding: utf-8 -*-
# Copyright 2010-2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this... |
import pytest
from validate import check_query_f, check_query
from remote_server import NodeGraphQL
from context import PytestConf
from conftest import use_action_fixtures, use_function_permission_fixtures
if not PytestConf.config.getoption('--test-inherited-roles'):
pytest.skip('--test-inherited-roles is missi... |
import numpy as np
from scipy.optimize import minimize
from enum import Enum
from itertools import combinations_with_replacement
class GrowthPolicy(Enum):
ALL_TERMS = 1
GROW = 2
PRUNE_AND_GROW = 3
class DeepInterpretablePolynomialNeuralNetwork:
def __init__(self, d_max, lambda_param, balance, fixed_ma... |
n = int(input())
s=""
b=[]
x=lambda:f",{b[0]}" if len(b)==1 else f",{b[0]}-{b[-1]}"
for i in input().split():
p = int(i)
if not b or b[-1]+1==p:
pass
else:
s+=x()
b=[]
b.append(p)
s+=x()
print(s[1:]) |
import numpy as np
from py_wake.site._site import UniformWeibullSite
from py_wake.wind_turbines import OneTypeWindTurbines
wt_x = [361469, 361203, 360936, 360670, 360404, 360137,
359871, 361203, 360936, 360670, 360404, 360137,
359871, 359604, 359338, 360936, 360670, 360404,
360137, 359871, 3596... |
# Generated by Django 2.0.2 on 2018-03-13 13:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('start', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userdatamodel2',
name='an',
... |
"""
Read in the cmsis/devinc/stm32f405xx.h header, extract relevant constants,
and create modstmconst.c.
This is not part of the automatic build process because stm32f405xx.h isn't
expected to change. After generating the file, some manual intervention is
needed to copy the new qstr definitions to qstrdefsport.h.
"""... |
import pygame as pg
from . import loaders
from .Entity import Entity
from .Const import *
class Mushroom(Entity):
def __init__(self, x_pos, y_pos, move_direction):
super().__init__()
self.rect = pg.Rect(x_pos, y_pos, 32, 32)
if move_direction:
self.x_vel = 1
else:
... |
"""
This file offers the methods to automatically retrieve the graph SW-100-4-0d3-trial2.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Dateti... |
from flask_wtf import FlaskForm
from flask_pagedown.fields import PageDownField
from wtforms import StringField, SubmitField, BooleanField, DateField, IntegerField, FileField
from wtforms.validators import DataRequired, Optional
class CollectionForm(FlaskForm):
name = StringField('Name*', validators=[DataRequired... |
#! /usr/bin/env python3
####################################################################
# Idea is to handle everything from the data frame
####################################################################
from configparser import ConfigParser, ExtendedInterpolation
import time
import numpy as np
import pandas ... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'django_prbac.tests.settings')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
'''
Translates pattern file into cloudformation template file.
'''
from logging import getLogger
from ..utils import helper
from ..utils.loader import save_template_to_file
logger = getLogger(__name__)
def run(pattern):
helper.ensure_folder()
template = pattern.dump()
file_path = helper.get_processed_tem... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'marbl_31919.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Im... |
from setuptools import setup
from setuptools import find_packages
from subprocess import check_output
#The following two functions were taken from the repo: https://github.com/pyfidelity/setuptools-git-version/blob/master/setuptools_git_version.py
def format_version(version, fmt='{tag}.{commitcount}'):
parts = ver... |
from unittest import mock
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from duffy import exceptions, shell
from duffy.database import model
from .util import noop_context
@pytest.mark.parametrize("with_ipython", (True, False))
@mock.patch("duffy.shell.IPython", n... |
import unittest
from hamcrest.core.core.isequal import equal_to
from hamcrest.library.collection.isdict_containingkey import *
from hamcrest_unit_test.matcher_test import MatcherTest
from .quasidict import QuasiDictionary
__author__ = "Jon Reid"
__copyright__ = "Copyright 2011 hamcrest.org"
__license__ = "BSD, see L... |
import os_translator.translator
|
import nltk
#nltk.download('wordnet')
nltk.download('punkt')
nltk.download('stopwords')
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import difflib
import pandas as pd
def word_extractor(sentence):
tokenizer = RegexpTokenizer(r'\w+')
tokens =tokenizer.tokenize(sentence)
toke... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2017-present MagicStack Inc. and the EdgeDB 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... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from django.core import mail
from django.utils import timezone
from exam import fixture
from mock import Mock
from sentry.digests.notifications import (
build_digest,
event_to_record,
)
from sentry.interfaces.stacktrace import Stackt... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
import numpy as np
from gym.spaces import Box
from metaworld.envs.env_util import get_asset_full_path
from metaworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv
class SawyerNutDisassembleEnv(SawyerXYZEnv):
def __init__(self, random_init=True):
liftThresh = 0.05
hand_low = (-0.5, 0.40, 0.05)
... |
# Import Modules
from ciscoconfparse import CiscoConfParse
# Parse Configuration File
cisco_config = CiscoConfParse("cisco_ipsec.txt")
# Find Crypto Objects without Specific Children
crypto_woaes = cisco_config.find_objects_wo_child(parentspec=r"^crypto map CRYPTO", childspec=r"set transform-set AES-SHA")
# Print Cr... |
from __future__ import print_function
from amitools.binfmt.BinImage import *
from HunkBlockFile import HunkBlockFile, HunkParseError
from HunkLoadSegFile import HunkLoadSegFile, HunkSegment
from HunkDebug import *
import Hunk
class BinFmtHunk:
"""Handle Amiga's native Hunk file format"""
def is_image(self, path)... |
import argparse
import json
import os
from pathlib import Path
from data import data_map
from metrics.ProcessedMetricsPrinter import ProcessedMetricsPrinter
from models import model_map
from server import server_map
from trainer import (
criterion_map,
ddp_hook_map,
ddp_model_map,
hook_state_map,
i... |
# -*- coding: utf-8 -*-
"""The Windows Registry plugin interface."""
import abc
from plaso.containers import time_events
from plaso.containers import windows_events
from plaso.lib import definitions
from plaso.parsers import plugins
class BaseWindowsRegistryKeyFilter(object):
"""The Windows Registry key filter in... |
''' Used libraries '''
import sys
import ctypes
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QByteArray, QDataStream, QIODevice
from PyQt5.QtWidgets import (QApplication, QDialog, QLabel, QHBoxLayout, QMessageBox, QPushButton, QVBoxLayout)
from PyQt5.QtNetwork import QLocalServer
from PyQt5.QtWid... |
"""Handle log in deep_trainer
You can create your own logger class following these examples.
By default the TensorBoard logger is used.
"""
from typing import Dict, List, Tuple
import torch.utils.tensorboard
class TrainLogger:
"""Base logger class. By default, do not log.
Each logger should define its ow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.