content stringlengths 5 1.05M |
|---|
import os
import shutil
import pytest
from PrognosAIs import Pipeline
CONFIG_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "test_data", "test_config.yaml"
)
CONFIG_FILE_CUSTOM = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "test_data", "test_config_custom_functions.yaml"
)... |
from pyzbar import pyzbar
import cv2
img_path = 'xx.TIF'
img = cv2.imread(img_path)
barcodes = pyzbar.decode(img)
for barcode in barcodes:
(x, y, w, h) = barcode.rect
# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
... |
NO_RESULTS_TEXT = '//div[@id="content"]//div[@class="row result"]/div/text()'
|
from typing import Any
from pathlib import Path
import inspect
import rootpath
import os
def obj_module_path(obj: Any) -> str:
"""Get a module path for any given object"""
fp = Path(inspect.getfile(obj))
rp = Path(rootpath.detect())
local_path = str(fp.relative_to(rp))
clean_path = os.path.spli... |
import sublime
import sublime_plugin
import re
import logging
import hyperhelpcore as hh
def log(*args):
print("[PythonDocs]", *args)
def plugin_loaded():
hh.initialize()
class PythonDocsOpen(sublime_plugin.TextCommand):
pkg = "PythonDocs"
pkg_info = None
def run(self, _: None, topic: str =... |
import pandas as pd
# Load PUMS records
df_pums_persons = pd.read_csv(r'R:\SyntheticPopulation_2018\group_quarters\input_files\seed_persons_gq.csv')
df_pums_households = pd.read_csv(r'R:\SyntheticPopulation_2018\group_quarters\input_files\seed_households_gq.csv')
# Load block group level group quarters data from OFM
... |
# Demo Python Numbers - Complex
'''
Python Numbers
There are three numeric types in Python:
* int
* float
* complex
Variables of numeric types are created when you assign a value to them.
To verify the type of any object in Python, use the type() function.
'''
# Complex numbers are written with a "j" as the imagi... |
from string import Template
# language=bash
download_command = Template(
"""
curl -L -s -o xz.tar.gz "https://tukaani.org/xz/xz-${version}.tar.gz"
"""
)
# language=bash
extract_command = Template(
"""
rm -rf "xz-${target}"
tar xf xz.tar.gz
mv "xz-${version}" "xz-${target}"
"""
)
# language=bash
make_command ... |
crypto_list = ["bitcoin", "ethereum", "monero"]
print(crypto_list)
crypto = crypto_list[-2]
print(crypto)
|
import pytest
from aioarango.collection import StandardCollection
from aioarango.database import StandardDatabase, TransactionDatabase
from aioarango.exceptions import (
TransactionAbortError,
TransactionCommitError,
TransactionExecuteError,
TransactionInitError,
TransactionStatusError,
)
from aioa... |
import os
os.path.dirname(os.path.abspath(__file__)+'/../../')
from QNetbots.core_bot_api.matrix_bot_api import MatrixBotAPI
from QNetbots.core_bot_api.mregex_handler import MRegexHandler
from QNetbots.core_bot_api.mcommand_handler import MCommandHandler
class Bot(object):
def __init__(self, USERNAME,PASSWORD,SE... |
print(int(input())%9) |
# noinspection PyUnresolvedReferences
import pypi_org.data.audit # noqa: F401
# noinspection PyUnresolvedReferences
import pypi_org.data.downloads # noqa: F401
# noinspection PyUnresolvedReferences
import pypi_org.data.languages # noqa: F401
# noinspection PyUnresolvedReferences
import pypi_org.data.licenses # n... |
import json
from enum import Enum
import requests
class AIxResource:
__url = "https://api.aixsolutionsgroup.com/v1/"
class RequestMethod(Enum):
GET = "GET"
POST = "POST"
PATCH = "PATCH"
DELETE = "DELETE"
def __init__(self, api_key):
"""
Initializes the AI... |
import string
from typing import Text, Dict, List, Optional, Set
import streamlit
LANGUAGES = {
"en": "English",
"de": "Deutsch"
}
LANGUAGE = streamlit.sidebar.selectbox(
"🌍 Language",
list(LANGUAGES.keys()),
format_func=lambda lang: LANGUAGES[lang]
)
SHOW_SOURCE_LINK_TEXT = {
"en": "Show l... |
""" Implement tasks for invoke.
"""
import os
import sys
import subprocess
from invoke import task
this_dir = os.path.dirname(__file__)
def call(*cmd):
sys.exit(subprocess.call(cmd, cwd=this_dir))
def get_node_exe():
node_exe = 'nodejs'
try:
subprocess.check_output([node_exe, '--version'])
... |
from .factory import make_airflow_dag, make_airflow_dag_containerized
__all__ = ['make_airflow_dag', 'make_airflow_dag_containerized']
|
import uuid
from .parser import Token, Node
def to_dot(ast):
result = [
'strict digraph "AST" {',
'size="16,14"; ratio = fill;'
]
_escape = lambda s: s.replace('"', r'\"')
def format_node(node, uid):
if isinstance(node, Token):
label = '{} [{}]'.format(*map(_es... |
import random
from unittest import TestCase, mock
from faker import Faker
from pyeti.eti_django.db import LOCKS, lock
fake = Faker()
srandom = random.SystemRandom()
class LockTests(TestCase):
def setUp(self):
transaction_patcher = mock.patch('pyeti.eti_django.db.transaction')
self.__transactio... |
psuedo_code = """
If the list is empty or has one item, it is sorted by definition.
This is our base case.
"""
###
print "merge sort"
count = 0
def merge_sort(alist):
"""list -> list
sorted from least to greatest
"""
#print("Splitting ", alist)
global count
#splitting list section
... |
"""Contains the functions and classes for specific and exact calculations"""
import numpy as np
import matplotlib.pyplot as plt
plt.clf()
plt.cla()
plt.close()
class Hamiltonian:
'''
This is a simple class to calculate the hamiltonian for a spin configuration
:param J: The ferromagnetic constant for the ma... |
from __future__ import unicode_literals, division, absolute_import
from flexget import plugin
from flexget import validator
class Magnets(object):
"""Removes magnet urls form the urls list. Rejects entries that have nothing but magnet urls."""
schema = {'type': 'boolean'}
@plugin.priority(0)
def on_... |
# Copyright 2015 The Bazel 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 required by applicable la... |
from sanic.blueprints import * |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from django.views.debug import get_safe_settings
class SafeSettings(object):
"""
Map attributes to values in the safe settings dict
"""
def __init__(self):
self._settings = get_safe_settings()
def __getatt... |
#!/usr/bin/env python3
import time
import math
from datetime import datetime
from time import sleep
import numpy as np
import random
import cv2
import os
import argparse
import torch
import sys
sys.path.append('./Eval')
sys.path.append('./')
from env import Engine
from utils_env import get_view,safe_path,cut_frame,po... |
# -*- coding: utf-8 -*-
import BaseHTTPServer
import cgi
import json
import os, subprocess
import sys
from BaseHTTPServer import HTTPServer
from datetime import datetime
import mxnet as mx
import numpy as np
import time
from config_util import parse_args, parse_contexts, generate_file_path
from create_desc_json import... |
import pytest
import os
import uuid
import random
import numpy as np
from rafiki.constants import UserType, ModelAccessRight
from rafiki.client import Client
from rafiki.config import SUPERADMIN_EMAIL
superadmin_email = SUPERADMIN_EMAIL
superadmin_password = os.environ['SUPERADMIN_PASSWORD']
# Details for mocks
DAT... |
#!/usr/bin/python3.4
#Client authentification
#coding: utf8
import os
from getpass import getpass
import hashlib
import socket
TCP_IP = '127.0.0.1'
TCP_PORT=6262
BUFFER_SIZE=100
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.li... |
"""
Django settings for {{ cookiecutter.project_name }} project.
"""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
import environ
########## PATH CONFIGURATION
BASE_DIR = dirname(dirname(__file__) + "../../../")
# Absolute filesystem path to the config directory:
CONFIG_ROOT =... |
# coding: utf-8
from .github import GithubApi
from .repository import RepositoryApi
|
import tornado.web
import tornado.gen
import json
import logging
from mickey.basehandler import BaseHandler
from mickey.groups import GroupMgrMgr
import mickey.redis
class OpenAttachKeepAliveHandler(BaseHandler):
@tornado.web.asynchronous
@tornado.gen.coroutine
def post(self):
data = json.loads(s... |
#
# PySNMP MIB module A3COM-HUAWEI-DOT11-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DOT11-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:49:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
"""
Convert json lines txt to csv with relevant columns
"""
import os
import argparse
import glob
from utils import read_tweets
RAW_TWEET_DIR = 'raw_tweet'
CSV_TWEET_DIR = 'out'
# maybe create os dir
if not os.path.exists(CSV_TWEET_DIR):
os.makedirs(CSV_TWEET_DIR)
def tocsv(lang_detection,include_current,data... |
# Copyright (C) 2009-2016, Quentin "mefyl" Hocquet
#
# This software is provided "as is" without warranty of any kind,
# either expressed or implied, including but not limited to the
# implied warranties of fitness for a particular purpose.
#
# See the LICENSE file for more information.
from .. import Builder, Node, P... |
"""
DB abstraction for Daoliproxy
"""
from daoliproxy.db.api import *
|
"""
The implementation of the `isqlite` command-line tool.
"""
import collections
import importlib
import shutil
import sqlite3
import sys
import tempfile
import traceback
import click
import sqliteparser
from tabulate import tabulate
from . import Database, Schema, migrations
# Help strings used in multiple places.... |
from django.urls import path
from .views import AdopterListView, AdopterCreateView, AdopterUpdateView
app_name = "adopters"
urlpatterns = [
path("adopters/", AdopterListView.as_view(), name="adopter-list"),
path("adopters/new", AdopterCreateView.as_view(), name="adopter-new"),
path("adopters/<int:pk>", Ad... |
# -*- coding: utf-8 -*-
from ._version import __version__, __version_info__
from .storage import LocalStorage
__all__ = ["__version__", "__version_info__", "LocalStorage"]
|
# This is an example which simulates the use case here: https://github.com/CoffeaTeam/coffea/blob/master/binder/muonspectrum_v1.ipynb
import time
import uproot
import uproot_methods
import awkward
from skyhookdmclient import SkyhookDM
import numpy
from coffea import hist
sk = SkyhookDM()
sk.connect('192.170.236.173',... |
import folium
import pandas as pd
#대학교 리스트를 데이터 프레임으로 변환
df = pd.read_excel('D:/5674-833_4th/part4/서울지역 대학교 위치.xlsx',engine= 'openpyxl')
#서울 지도 만들기
seoul_map = folium.Map(location=[37.55,126.98], tiles= 'Stamen Terrain',
zoom_start= 12)
df.set_index('학교',inplace = True)
#대학교 위치 정보를 Marker로 표... |
from django.db import IntegrityError
from django.test import TestCase
from .models import Profile, User
class UserTest(TestCase):
""" Test module for Puppy model """
def setUp(self):
User.objects.create(
email='mario.rossi@gmail.com',
password="password",
first_nam... |
#!/usr/bin/env python
#
# 파이썬을 사용해서 JSON과 JSON Lines 파일을 읽고 쓰기
#
import sys, os, re
import json
import codecs
ary_of_objects = [
{'name': 'Russell Jurney', 'title': 'CEO'},
{'name': 'Muhammad Imran', 'title': 'VP of Marketing'},
{'name': 'Fe Mata', 'title': 'Chief Marketing Officer'},
]
path = "/tmp/test.jsonl"... |
# coding=utf-8
"""
Wrapper for various check actions for different objects.
"""
import os
import socket
import subprocess
from typing import Optional, Dict, List
from is_it_up.exceptions import IsItUpException
_ = Optional, Dict, List
class IsItUpBase(object):
def __init__(
self,
host: str,
... |
from __future__ import annotations
from typing import Any, Generator, Optional, Tuple, Union
import numpy as np
from numpy.random import RandomState
from sklearn.model_selection import BaseCrossValidator
from sklearn.utils import check_random_state, resample
from ._typing import ArrayLike
class Subsample(BaseCross... |
from django import forms
from django.forms.models import BaseInlineFormSet
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import Organisation, CategoryTemplate, Category, Contract
from .admin_forms import CategoryTemplateAdminForm
class CategoryInline(admin.Stac... |
"""Define common test utilities."""
import os
TEST_ALTITUDE = "1609.3"
TEST_API_KEY = "12345"
TEST_LATITUDE = "51.528308"
TEST_LONGITUDE = "-0.3817803"
def load_fixture(filename):
"""Load a fixture."""
path = os.path.join(os.path.dirname(__file__), "fixtures", filename)
with open(path, encoding="utf-8") ... |
import os
import re
import pickle
import functools
import logbook
from pathlib import Path
from subprocess import DEVNULL, Popen
from pathos.multiprocessing import ProcessingPool
import pandas as pd
from ete3 import Tree
from genbankqc import config
import genbankqc.genome as genome
class Species:
def __init_... |
# -*- coding:utf-8 -*-
from appium import webdriver
import time
# server启动参数
desired_caps = {}
# 设备参数
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '192.168.56.101:5555'
# app参数
desired_caps['appPackage'] = 'cn.goapk.market'
desired_caps['appActivity... |
from collections import Counter
from typing import List, Union, Optional, Set, Dict
import numpy as np
from docqa.dataset import Dataset, TrainingData, ListDataset, ListBatcher
from docqa.utils import ResourceLoader, flatten_iterable, max_or_none
from docqa.configurable import Configurable
from docqa.data_processing.... |
# Last version 03102019, mod: limite to while iteration
def DP_simp(r,AA0,nstd,sm = 5):
import pandas as pd
import numpy as np
from running_mean import running_mean
AA=running_mean(AA0,sm)#[sm-1:]
rr=r[(sm-1)/2:-(sm-1)/2]#pd.rolling_mean(r,sm)[sm-1:]
Er = AA - AA0[(sm-1)/2:-(sm-1)/2]#[sm... |
#!/usr/bin/python2
from scapy.all import *
#dest = input("Destination: ")
#dest = raw_input("\nDestination: ")
#destport = input("Destination port: ") #Porta de destino
dest = '10.0.0.99'
destport = '1234'
ip = IP(dst=dest)
udp = UDP(dport=int(destport),sport=40000)
raw = Raw(b'Quero um video 720p')
pkt = ip/ud... |
"""
Unit-tests for orderby module public interface, in the way
it is supposed to be used in sorted() and others
"""
from orderby import asc, desc, orderby
from unittest import TestCase
TEST_DATA_PERSONS = (
{'id': 0, 'lastname': 'Smith', 'firstname': 'John', 'age': 42, 'score': 50},
{'id': 1, 'lastname': 'Smit... |
# coding: utf-8
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1 </span>Introduction</a></span></li><li><span><a href="#Get-the-vancouver-image" data-toc-mod... |
from QtModularUiPack.Framework.Math.Spectrogram import spectrogram
|
from regression_tests import *
class Test001(Test):
settings=TestSettings(
tool='fileinfo',
args='--verbose --json',
input='dropped.ex'
)
def test_delayed_imports_detection(self):
assert self.fileinfo.succeeded
self.assertEqual(self.fileinfo.output['importTable']['n... |
from beaker.middleware import SessionMiddleware
from bottle import Bottle
from jumpscale.loader import j
from jumpscale.packages.auth.bottle.auth import SESSION_OPTS, admin_only, login_required
from jumpscale.packages.polls.chats.threefold import VOTES
from jumpscale.sals.chatflows.polls import all_users
app = Bottle... |
import os
import json
import urllib
import urllib.request
from typing import Dict, Any
SLACK_URL = "https://slack.com/api/chat.postMessage"
def create_wayback_machine_response(event: Dict[str, Any]) -> str:
""" """
elements = event['blocks'] \
.pop()['elements'] \
.pop()['elements']
lin... |
# 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 u... |
import unittest
from mock import MagicMock
import fdm.analysis.analyzer
from fdm import Mesh
from fdm.analysis.analyzer import (Output, create_variables, OrderedNodes)
from fdm.geometry import Point
def create_mesh(node_number, virtual_nodes=(), delta=2.):
length = delta*node_number
return Mesh(
[Po... |
import re
from oelint_parser.cls_item import Variable
from oelint_adv.cls_rule import Rule
from oelint_parser.helper_files import get_valid_package_names, get_valid_named_resources, expand_term
from oelint_parser.constants import CONSTANTS
class VarPnBpnUsage(Rule):
def __init__(self):
super().__init__(i... |
import sys
import time
import os
import re
import datetime
from enum import IntEnum
from os.path import expanduser
from bs4 import BeautifulSoup, SoupStrainer
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.supp... |
from rest_framework import serializers
from app.models import CountTrue
class UserSerializer(serializers.Serializer):
"""
A serializer class for serializing the SlackUsers
"""
id = serializers.IntegerField()
firstname = serializers.CharField()
lastname = serializers.CharField()
photo = ser... |
from os import walk, path
from glob import glob
README = '''
Recursively searching for *.js files inside 'src' folder and
checking if the file is flowed ('// @flow' is on the first line)
'''
DELIM, PATH = '---------------------------------------------------------------', 'src'
print(README)
print(DELIM)
files = [y ... |
if False:
from lib.Processing3 import *
"""
長方形の分割によるユークリッド互除法の可視化(正方形の再帰的な分割)
"""
add_library("controlP5")
SIZE_X = 500
SIZE_Y = 500
num_a = 10
num_b = 6
ratio = 1.0 * num_b / num_a
threshold = 40
def setup():
size(SIZE_X, SIZE_Y)
colorMode(HSB, 1)
global cp5
cp5 = ControlP5(this)
cp5.addS... |
# coding=utf-8
# Copyright 2018 The TF-Agents 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... |
"""Gibbs sampler"""
import tensorflow_probability as tfp
__all__ = ["GibbsStep", "DeterministicScanKernel", "flatten_results"]
tfd = tfp.distributions # pylint: disable=no-member
mcmc = tfp.mcmc # pylint: disable=no-member
def flatten_results(results):
"""Results structures from nested Gibbs samplers sometim... |
import numpy as np
import torch
from torch import nn
import sys
import util
class DataLoader(nn.Module):
"""Data loader module for training MCFlow
Args:
mode (int): Determines if we are loading training or testing data
seed (int): Used to determine the fold for cross validation experiments or r... |
# -*- coding: utf-8 -*-
from slacker import Slacker
class Slack(object):
def __init__(self, token, channels=None, username=None, icon_url=None):
self.slack = Slacker(token)
self.username = username
self.icon_url = icon_url
self.channels = channels if channels else self.list_channel... |
"""This is an auto-generated file. Modify at your own risk"""
from typing import Awaitable, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from cripy import ConnectionType, SessionType
__all__ = ["CSS"]
class CSS:
"""
This domain exposes CSS read/write operations. All CSS ob... |
import sys
import pathlib
include_fileendings = ["py", "txt", "yml", "cfg", "rst", "md", "ini", "in"]
include_files = ["Makefile"]
exclude_files = ["rename_package.py"]
args = sys.argv[1:]
new_name = args[0]
this_dir = pathlib.Path('.').absolute()
for drc in this_dir.glob("**/*"):
if drc.is_dir():
new_d... |
# Generated by Django 3.0.5 on 2020-07-03 20:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('home', '0018_auto_20200627_1023'),
]
operations = [
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2018 JMatica Srl
#
# This file is part of apitestframework.
#
# 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.apa... |
"""Models for projects.
"""
from sqlalchemy.ext.associationproxy import association_proxy
from app import db
from base import Base
from .log import Log
from .association_objects import ProjectsUsers
class Project(db.Model, Base):
"""A WordSeer project for a collection of documents.
Attributes:
name (... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'andyguo'
from deco import data_type_validation
from numbers import Number
from vector import Vec2f, Vec3f, Vec4f
class MatrixBase(object):
__slots__ = ['data']
dimension = (1, 1)
def __eq__(self, other):
if isinstance(other, MatrixBa... |
from .centroidal_phi import CentroidalPhi, EESplines
from .contact_sequence_wrapper import ContactSequenceWrapper
from .problem_definition import createMultiphaseShootingProblem
from .spline_utils import polyfitND
|
from common.models import *
from common.toontown import *
from common.threads import *
|
import sys
#sys.path.append('/scratch/pradap/python-work/py_entitymatching')
|
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
# FEWTURE-BOOM: do not report me (not an orphan)
# FEWTURE-I-AM-AN-ORPHAN: report me
# FEWTURE-I-AM-NOT-AN-ORPHAN: do not report me (pragma) no-check-fixmes
|
from machine import Pin
from time import sleep
# both esp8266 and esp32 have led on pin 2
led = Pin(2, Pin.OUT)
while True:
led.value(not led.value())
sleep(1)
|
from sys import path
path.append("../APTED/apted")
path.append("../ML_Models/ObjectDetection")
path.append("util/")
import caption_generator
import constants
import json
import requests
import datetime
import parse_show_tree
import urllib
from apted import APTED, PerEditOperationConfig
import apted.helpers as apth
imp... |
from flask_wtf import FlaskForm
from wtforms import StringField,SelectField,TextAreaField,SubmitField
from wtforms.validators import Required, Email
from wtforms import ValidationError
from ..models import Subscription
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Implement experimental syncing methods.
"""
from __future__ import annotations
from meerschaum import Pipe
from meerschaum.plugins import add_plugin_argument, make_action
from meerschaum.utils.typing import Optional, Any, List, SuccessTuple
from coll... |
from .expected_gradients import AttributionPriorExplainer
from .fixup import mixup_data, mixup_criterion
from .visualization import show_pil_image, pil_img, visualize_attrs |
#!/bin/env python
# -*- coding: utf8 -*-
import pymysql as pm
def check_and_connect(args):
if 'host' not in args or not args['host']:
raise AttributeError()
if 'user' not in args or not args['user']:
raise AttributeError()
if 'database' not in args or not args['database']:
raise At... |
# GIS4WRF (https://doi.org/10.5281/zenodo.1288569)
# Copyright (c) 2018 D. Meyer and M. Riechert. Licensed under MIT.
from typing import Tuple, Callable
import os
import re
from functools import partial
from gis4wrf.core.util import export, gdal, get_temp_dir, get_temp_vsi_path, remove_dir, remove_vsis
from gis4wrf.... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# This script reuses some code from https://github.com/nlpyang/BertSum
"""
Utility functions for downloading, extracting, and reading the
CNN/DM dataset at https://github.com/harvardnlp/sent-summary.
"""
from textsumm.models.transformer... |
#!/usr/bin/env python
import sys
import pcapy
from scapy import *
from impacket.ImpactDecoder import *
try:
conf.verb=0
except NameError:
# Scapy v2
from scapy.all import *
conf.verb=0
if len(sys.argv) != 2:
print "Usage: ./replay.py <iface>"
sys.exit(1)
interface=sys.argv[1]
max_bytes = 20... |
from arch.api.utils import log_utils
from arch.api.proto import feature_scale_meta_pb2
from arch.api.proto import feature_scale_param_pb2
from arch.api.model_manager import manager as model_manager
from federatedml.feature.min_max_scaler import MinMaxScaler
from federatedml.feature.standard_scaler import StandardScaler... |
from django.urls import path
from .import views
urlpatterns=[
path('',views.index,name='index'),
path('register',views.register,name='register'),
path('login',views.login,name='login'),
path('data',views.data,name='data'),
path('predict',views.predict,name='predict'),
path('logout',views.logout... |
import html
import arrow
from bs4 import BeautifulSoup
from jinja2 import Template
from digesters.base_digester import BaseDigester
class RedditNotificationDigester(BaseDigester):
def __init__(self, store_writer, userId):
super(RedditNotificationDigester, self).__init__()
self.store_writer = sto... |
def fun1(y, z):
x = y % 3 + z * 2
if x > 5 and y <= 10 or z == 0:
return x + y + z
elif z < 3:
return z * z * z
return x
def fun2(n):
if n <= 0:
return 0
cnt = 0
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
cnt = cnt + 1
return cnt
def fun2r(n):
if n... |
import re
from terroroftinytown.client import errors
from terroroftinytown.services.isgd import IsgdService
from terroroftinytown.services.rand import HashRandMixin
from terroroftinytown.services.status import URLStatus
from terroroftinytown.six.moves import html_parser
class VgdService(IsgdService):
def parse_b... |
from django.db import models
# Create your models here.
class Order(models.Model):
title = models.CharField(max_length=32)
def __str__(self):
return self.title
class Food(models.Model):
title = models.CharField(max_length=32)
|
# -*- coding: utf-8 -*-
"""
--------------------------------------
@File : __init__.py
@Author : maixiaochai
@Email : maixiaochai@outlook.com
@Created on : 2020/5/22 15:39
--------------------------------------
"""
from copy import deepcopy
from flask import jsonify
from flask_restful import Resource, ... |
__author__ = 'antonellacalvia'
import AST as Tree
def constantsPass(tree, funcs):
vars = {}
def run(n, pos= 0, name= ""):
for iter in range(len(n.nodes)):
i = n.nodes[iter]
if not n.isEnd():
run(i, iter, i.name if type(i) in [Tree.FuncBraceOpen, Tree.FuncBody] o... |
from sqlalchemy.ext.asyncio import create_async_engine
from source.infrastructure.settings import application_settings
engine = create_async_engine(
application_settings.postgres_url,
pool_size=50,
max_overflow=0
)
|
# -*- coding: utf-8 -*-
from collections import OrderedDict
from pyramid.view import view_config
from chsdi.models.bod import Translations
class TranslationService(object):
def __init__(self, request):
self.geodataStaging = request.registry.settings['geodata_staging']
self.cbName = request.par... |
import serial
import time
ser = serial.Serial('COM3', 115200, timeout=5)
time.sleep(5)
#<Timestamp, track number, MIDI channel, type, key, value>
ser.write(bytes(b'<0,0,0,8,0,0>'))
ser.write(bytes(b'<0,1,0,1,52,210>'))
ser.readline()
ser.write(bytes(b'<12,1,0,1,52,126>'))
ser.readline()
ser.write(bytes(b'<65,1,0,1,52,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.