content stringlengths 5 1.05M |
|---|
#! /usr/bin/python3
import json
import os
from .color import Color
from .transport import Transport
class CMSync:
"""Sync directories and files based on the specifications of the json file
"""
def __init__(self, config_file='sync.json'):
"""
Loads the JSON file and executes the sync bas... |
import logging
import dateutil.parser
from udata.models import Dataset
from .utils import check_url, UnreachableLinkChecker
log = logging.getLogger(__name__)
class CroquemortLinkChecker(object):
"""Croquemort link checker implementation.
The main interface is the `check` method.
"""
def _format_r... |
"""
If a "function" is in the plt it's a wrapper for something in the GOT.
Make that apparent.
"""
import vivisect
import envi
import envi.archs.i386 as e_i386
import envi.archs.i386.opcode86 as opcode86
def analyze(vw):
"""
Do simple linear disassembly of the .plt section if present.
"""
for sva,ssi... |
#!/usr/bin/env python3
"""
Module containing functions to calculate structural environment profiles of AAs
"""
# TODO Tests to make sure these are producing correct profiles
from collections import defaultdict
import numpy as np
from Bio.SeqUtils import seq1
from Bio.Alphabet.IUPAC import protein as protein_alphabet
... |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
"""Manager for causal analysis."""
import pandas as pd
from econml.solutions.causal_analysis import CausalAnalysis
from pathlib import Path
from responsibleai._internal.constants import ManagerNames
from responsibleai._managers.base_manager impo... |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
def get_edge_indices(img_metas,
downsample_ratio,
step=1,
pad_mode='default',
dtype=np.float32,
device='cpu'):
"""Function to fil... |
from collections import OrderedDict
import numpy as np
import pytest
from rest_framework.test import APIClient
from standardizing_api.transformer import Transformer
@pytest.fixture(scope='module')
def transformer():
transformer = Transformer()
return transformer
@pytest.fixture
def validated_data():
v... |
import random
class EventSpawner(object):
def __init__(self, asteroidController, powerupController, stats):
self.asteroidController = asteroidController
self.powerupController = powerupController
self.gameStats = stats
self.events = {self.asteroidController.spawnBasicAsteroid: 1... |
# coding: utf-8
# create by tongshiwei on 2019/7/2
from .train_valid_test import train_valid_test
from .download_data import get_data |
# -*- coding: utf-8 -*-
from hangulize import *
class Azerbaijani(Language):
"""For transcribing Azerbaijani."""
__iso639__ = {1: 'az', 2: 'aze', 3: 'aze'}
__tmp__ = ',;'
vowels = 'aAeIioOuU'
cs = 'bcCdfgGhjklmnNpqrsStvxz'
vl = 'CfhkKpsStx'
notation = Notation([
('-', '/'),
... |
from django.core.management.base import BaseCommand
from audit_log.tasks import clear_audit_log_entries
class Command(BaseCommand):
help = "Clear old sent audit log entries from database"
def handle(self, *args, **kwargs):
clear_audit_log_entries()
|
import typing
from pycspr.types import cl_types
from pycspr.types import CL_TypeKey
def encode(entity: cl_types.CL_Type) -> typing.Union[str, dict]:
"""Encodes a CL type as a JSON compatible string or dictionary.
:param entity: A CL type to be encoded.
:returns: A JSON compatible string or dictionary.
... |
"""This module defines a Pulumi component resource for building ECS Fargate Services.
This module can accept a load balancer, if the caller chooses, but it is not required.
Included:
- ECS Cluster
- ECS Service
- ECS Task Definition - Single image task or multiple images (sidecar)
- EC2 Security Group(s)
Optional:
-... |
import time
from gradient_utils import metrics
class Settings(object):
start_time = None
tensorboard_watchers = []
class Init(object):
def __init__(self):
self._settings = Settings()
def init(self, sync_tensorboard):
self._settings.start_time = time.time()
if sync_tensorboar... |
def main():
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import sys, os
sys.path.append("../../..")
import procedural_city_generation
from procedural_city_generation.roadmap.config_functions.Watertools import Watertools
import Image
import numpy as np
img=np.dot... |
"""SOMClustering class.
Copyright (c) 2019-2021 Felix M. Riese.
All rights reserved.
"""
import itertools
from typing import List, Optional, Sequence, Tuple
import numpy as np
import scipy.spatial.distance as dist
from joblib import Parallel, delayed, effective_n_jobs
from sklearn.decomposition import PCA
from skle... |
import os.path as op
# import plotting as cyplot
# from biplot import biplot
# import plotting as cyplot
# import cycluster as cy
import matplotlib.pyplot as plt
import scipy.stats.stats
import numpy as np
import palettable
import itertools
import seaborn as sns
import statsmodels as sm
# sys.path.append('C:/Users/li... |
# 推出系统
import sys
# 游戏开发模块
import pygame
# 导入配置文件
from settings import Settings
# 导入飞船
from ship import Ship
# 导入 game_function模块
import game_function as gf
# 导入子弹编组
from pygame.sprite import Group
# 导入游戏状态
from game_stats import GameStats
def run_game():
# 初始化游戏,并创建一个屏幕对象
pygame.init()
ai_settings = Set... |
#******************************#
# Project: Dictionary practice
#
# Version: 1.0
# Author: Bruce Stull
# Date: December 6, 2021
#******************************#
import random
# Initialize dictionaries. This isn't neccesarily neccessary, the memory allotment for program space is reset each time script is r... |
import os
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
ENVIRONMENT = "production"
app = Flask(__name__)
app.secret_key = str(os.urandom(16))
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0
# Changes to the HTML files are reflected on the website without having to rest... |
from docx.table import Table
from sane_doc_reports.conf import SHOULD_HAVE_12_GRID
from sane_doc_reports.populate.Report import Report
from tests import utils
from tests.utils import _transform
def test_pie_chart_in_report():
report = Report(*_transform('elements/pie_chart.json'))
report.populate_report()
... |
"""Unit tests of authorization records."""
import pytest
from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only
@pytest.mark.usefixtures("authorization_record_class_fixture", "authorization_record_test_fixture")
class TestAuthorizationRecord(object):
"""Tests for Au... |
from typing import Iterable
_sentry = object()
class DoublyLinkedListNode(Iterable):
__slots__ = ("prev", "next", "key", "result")
def __init__(self, key=_sentry, result=None):
self.prev = self
self.next = self
self.key = key
self.result = result
def __iter__(self):
... |
from engine.map_tile import *
from engine.map import Map
import os
def local_path(path):
return os.path.abspath(os.path.join(__file__, os.pardir, path))
# Map xcf location
xcf =''
# Map tile layer 0
l0 = [
]
# Map tile layer 1
l1 = [
]
# Warp data
warp = {
None: {
None: (False, None),
}
}
d... |
import os
from c2cgeoform.routes import register_models, table_pregenerator
def includeme(config):
config.add_static_view('node_modules_for_insider', 'c2cgeoportal_admin:node_modules')
config.add_static_view(
'node_modules_for_outsider',
'{}:node_modules'.format(config.root_package.__name__))
... |
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2015 Bitcraze AB
#
# Cr... |
from flask import Blueprint, jsonify
from api.helper import *
from api.exceptions import *
smogonapi = Blueprint('smogonapi', __name__)
@smogonapi.route('/set/<generation>/<pokemon>')
def getDataNoForm(generation, pokemon):
try:
if pokemon.isdigit(): dictval = extractData(int(pokemon), int(generation))
... |
# 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 ... |
orders = []
def add_order(name, flavor, observation=None):
order = {}
order['name'] = name
order['flavor'] = flavor
order['observation'] = observation
return order
orders.append(add_order('Mario', 'Pepperoni'))
orders.append(add_order('Pirao', 'Rola', 'Prefiro pegar o Ordonha'))
for order in or... |
# -*- coding: utf-8 -*-
import os
import warnings
from setuptools import setup
from setuptools import find_packages
requirements = [
'setuptools',
'networkx',
'jpype1-py3',
'konlpy',
]
if os.name == 'nt':
warnings.warn("See http://konlpy.org/en/latest/install/#id2 to properly install KoNLPy.", ... |
# pylint: disable=unused-import
# flake8: noqa: F401
try:
# Python 3.8+
from typing import Protocol
except ImportError:
Protocol = object # type: ignore
|
# coding: utf-8
import smtplib
import urllib.request
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import common.lark_common.model.common_model as common_model
import common.lark_common.utils as lark_utils
from jinja2 import Template
from Ba... |
# Copyright 2021 eprbell
#
# 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, soft... |
#!/usr/bin/python3
"""Platform for light integration."""
import logging
from abc import ABC
from datetime import timedelta
from typing import Callable, List, Any
import homeassistant.components.lock
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistan... |
from flask_restx import Namespace, fields
product_ns = Namespace(
"Products",
description="Products related operations",
# # path="/products",
# path="/api/v1/products"
path="/api/v1"
)
products = product_ns.model("products", {
"id": fields.Integer(readonly=True),
"product_name": fields.S... |
'''
Original code:
https://github.com/idgmatrix/pygame-physics/blob/master/pygame_bouncing_ball.py
@author: kaswan
Modified:
@author: mandaw2014
'''
from mandaw import *
mandaw = Mandaw("Bouncing Ball!")
ball = GameObject(mandaw, "ellipse")
ball.center()
ball.ballx, ball.bally = mandaw.width / 2, mandaw.height / 2... |
#!/usr/bin/env python
# example dragndrop.py
import pygtk
pygtk.require('2.0')
import gtk
import string, time
import gtkxpm
class DragNDropExample:
HEIGHT = 600
WIDTH = 600
TARGET_TYPE_TEXT = 80
TARGET_TYPE_PIXMAP = 81
fromImage = [ ( "text/plain", 0, TARGET_TYPE_TEXT ),
( "image/x... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import configparser
import os
with open(os.path.join(os.path.dirname(__file__), "pygetpapers", "config.ini")) as f:
config_file = f.read()
config = configparser.RawConfigPars... |
from typing import Any, Optional
from automation.models import Automation
from celery import shared_task
from automation.actions.action_mqtt_publish import mqtt_publish
from automation.actions import Triggers
from automation.dataclasses import OnMotionData
from devices.models import Device
def _run_automations(trigg... |
# Generated by Django 2.2.2 on 2019-11-27 16:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
# from django.contrib.auth import views as auth_views
from django.urls import path, include
from .views import IndexView
urlpatterns = [
path('api/', include('api.urls', namespace='api')),
path('forms/... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
from typing import Any, Sequence
from click import style
def list2str(seq: Sequence[Any]) -> str:
# Source: https://stackoverflow.com/a/53981846
# seq = [str(s) for s in seq]
seq = [style(str(s), underline=True) for s in seq]
if len(seq) < 3:
return " and ".join(seq)
return ", ".join(s... |
#!/usr/bin/env python3
# to run this, run the following command from the top level directory output by benchmark
# find . -name "synth-*.log" -print0 | sort -z | xargs -0 tail -n 1 | python dump.py "x" > out.csv
# the regular expression assumes that relevant outputs are in "x-[machine].log"
# where x should be specif... |
from biothings.web import connections
import logging
logging.basicConfig(level='DEBUG')
def test_es_1():
client = connections.es.get_client('localhost:9200')
print(client.info())
def test_es_2(): # see if the client is reused
client1 = connections.es.get_client('localhost:9200')
client2 = connectio... |
*** Error at (7,9): can not reference a non-static field 'i' from static method 'main'
*** Error at (9,24): can not reference a non-static field 'i' from static method 'main'
*** Error at (13,24): can not reference a non-static field 'i' from static method 'main'
|
"""
Cosmology.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on 2010-03-01.
Description:
"""
import os
import numpy as np
from scipy.misc import derivative
from scipy.optimize import fsolve
from scipy.integrate import quad, ode
from ..util.Math import interp1d
from ..util.Paramete... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import argparse
import ipaddress
import syslog
import json
import time
from enum import Enum
from swsssdk import ConfigDBConnector
os.environ['PYTHONUNBUFFERED']='True'
PREFIX_SEPARATOR = '/'
IPV6_SEPARATOR = ':'
MIN_SCAN_INTERVAL = 10 ... |
import time
import os
import requests
import unittest
import numpy as np
import json
import sys
import numba
import uproot
import hepaccelerate
import hepaccelerate.backend_cpu as backend_cpu
import hepaccelerate.kernels as kernels
from hepaccelerate.utils import Results, Dataset, Histogram, choose_backend, LumiMask
... |
import argparse
import os
import time
import pybullet_planning as pp
from termcolor import cprint
import integral_timber_joints
from integral_timber_joints.planning.robot_setup import load_RFL_world
from integral_timber_joints.planning.rhino_interface import get_ik_solutions
from integral_timber_joints.planning.state... |
from time import sleep
print ('Bem vindo a seleção de aluguel de viaturas! Por favor, indique a classe do carro que pretende alugar :')
carro = int (input("""De momento apenas temos 2 classes :
[0] Carro Popular
[1] Carro de Luxo
"""))
if carro == 0:
Carropopular=90
print ('Carro Popular - $90 por dia')
... |
"""Create collage from images in a folder."""
from argparse import ArgumentParser
from pathlib import Path
from collamake.make import CollaMake
if __name__ == "__main__":
parser = ArgumentParser(description="A simple collage maker")
parser.add_argument("-f", "--file", type=Path, required=True)
args = pars... |
import asyncio
from binance_asyncio.endpoints import MarketDataEndpoints
async def main():
api_key = '<insert your api key here>'
market_data = MarketDataEndpoints(api_key=api_key)
# the first parameter is required, the rest are all optional and shawows the names of the binance api
# https://github.co... |
from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required
from boards.views import BoardUpdateView, BoardDeleteView, BoardCreateView, \
BoardListView, DashboardView
urlpatterns = [
url(r'^b/', include([
url(r'^(?P<pk>\d+)/', include([
url(r'^edit/... |
import random
import os
import time
from wabbit_wappa import *
def test_namespace():
namespace = Namespace('MetricFeatures', 3.28, [('height', 1.5), ('length', 2.0), 'apple', '1948'])
namespace_string = namespace.to_string()
assert namespace_string == 'MetricFeatures:3.28 height:1.5 length:2.... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 13:48:55 2017
@author: Administrator
"""
import config
import time
from globalMap import globalMap
from multiprocessing import Manager
class resultCount:
__threadCount=Manager().Value('c',0)
__totalCount=Manager().Value('i',0)
__successCount=Manager().Valu... |
#! /usr/bin/env python3
# Jan-18-2019
import os, sys
import pysam
from collections import defaultdict
def alignment_reads_snp_count(line,snp,quality_score_threshold=30):
strain1, strain2, match, mismatch = 0, 0, 0, 0
for align in line.get_aligned_pairs(matches_only=True):
if not align[1] in snp[line.... |
# Time: seat: O(logn), amortized
# leave: O(logn)
# Space: O(n)
# In an exam room, there are N seats in a single row,
# numbered 0, 1, 2, ..., N-1.
#
# When a student enters the room,
# they must sit in the seat that maximizes the distance to the closest person.
# If there are multiple such seats, they sit in... |
gocardless.client.new_bill_url(30.00, name="Example payment") |
from TextRank import Textrank
import pickle
from keras.preprocessing.text import Tokenizer
from gensim.models import word2vec
import numpy as np
from scipy import spatial
import re
import nltk
nltk.download('stopwords')
def cleanTex(descrlist):
REGEX_URL = r"(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.... |
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.linear_model import LinearRegression as SKLR
'''
A simple Gaussian Bayesian Classifier
'''
class LinearRegression(BaseEstimator, Reg... |
import unittest
import responses
import urllib
from ksql.api import BaseAPI
class TestBaseApi(unittest.TestCase):
@responses.activate
def test_base_api_query(self):
responses.add(responses.POST, "http://dummy.org/query", body="test", status=200, stream=True)
base = BaseAPI("http://dummy.org")... |
"""
Potentials in ultracold atom experiments are typically constructed using
Gaussian laser beams, here we provide some definitions that will make it easy
to assemble a generic optical dipole potential.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from vec3 import vec3, cross
import sc... |
import InputReader
def recuresiveGame(player1cards, player2cards):
states = []
while len(player1cards) > 0 and len(player2cards) > 0:
state = [player1cards.copy(), player2cards.copy()]
if state in states:
return 1, player1cards, player2cards
states.append(state)
w... |
from dos.open_api import OpenAPI
from dos.flask_wrappers import wrap_validation, wrap_handler, wrap_route
from flask import Flask, redirect, jsonify, url_for, render_template
from .api.dog import get as dog_get
from .api.cat import get as cat_get
def create_app():
app = Flask(__name__)
open_api = OpenAPI("P... |
import math
n = float(input("Digite um numero real: "))
print("sua porção inteira é {}".format(math.floor(n))) |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BaseContent(models.Model):
ACTIVE_CHOICES = ((0, 'Inactive'), (2, 'Active'),)
active = models.PositiveIntegerField(choices=ACTIVE_CHOICES,
default=2)
created = ... |
from Artesian._Query.QueryParameters.QueryParameters import _QueryParameters
from Artesian._Query.Config.VersionSelectionConfig import VersionSelectionConfig
class VersionedQueryParameters(_QueryParameters):
def __init__(self, ids, extractionRangeSelectionConfig, extractionRangeType, timezone, filterId, granularit... |
from geotools.utils.polygon import Polygon
import time
def main():
p = Polygon([
[2.3957061767578125, 48.89812957181126],
[2.399139404296875, 48.890906639609454],
[2.3996543884277344, 48.88413419286922],
[2.4090957641601562, 48.8801831753449],
[2.4127006... |
import math
# 11’den 99’a kadar döngünün oluşturulması.
for i in range(11, 99):
# “x”e yeni değerinin atanması
x = 2
j = 0
# “x” ile “kök(i)+1” eşit olmadığı sürece:
# “x” değeri hiçbir zaman (kök(i)+1) değeri ile “i”yi bölemez.
# Bu yüzden bu değerin (kök(i)+1) üstünü kontrol etmeye gerek yoktu... |
"""
api.video
api.video is an API that encodes on the go to facilitate immediate playback, enhancing viewer streaming experiences across multiple devices and platforms. You can stream live or on-demand online videos within minutes. # noqa: E501
Contact: [email protected]
"""
import os # noqa: F401
im... |
# coding=utf-8
import logging
import requests
class Request(object):
""" Simplifies querying bandcamp that protects from python-requests User-Agent """
headers = {'User-Agent': 'bandcamp_player/0.1'}
@staticmethod
def get(url) -> requests.Response:
""" :returns: Response from bandcamp """
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 19:52:05 2017
@author: vgor
"""
import re
from collections import Counter
#acording to J. Mol. Biol. 157:105-132(1982).
AA_hidropaticity = {
"A": 1.800,
"R": -4.500,
"N": -3.500,
"D": -3.500,
"C": 2.500,
"Q": -3.500,
"E": -3.500,
"G":... |
import zeit.cms.content.interfaces
import zeit.cms.tagging.interfaces
class IExampleContentType(
zeit.cms.content.interfaces.ICommonMetadata,
zeit.cms.content.interfaces.IXMLContent):
"""A type for testing."""
keywords = zeit.cms.tagging.interfaces.Keywords(
required=False,
d... |
# coding: utf-8
"""
Hydrogen Atom API
The Hydrogen Atom API # noqa: E501
OpenAPI spec version: 1.7.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class Overflow(object):
"""NOTE: ... |
"""
This module contains classes to describe objects such as Datasources on
sensor Instruments etc
"""
from ._base import BaseModule
from ._cranfield import CRANFIELD
from ._crds import CRDS
from ._datasource import Datasource
from ._eurocom import EUROCOM
from ._footprint import Footprint
from ._gcwerks import... |
"""
Run supervised segmentation experiment with superpixels and training examples
Pipeline:
1. segment SLIC superpixels
2. compute features (color and texture)
3. estimate model from single image or whole set
4. segment new images
.. note:: there are a few constants to that have an impact on the experiment,
see... |
import os
import sys
path = os.path.dirname(os.path.realpath(__file__))
pythonpath = path.rpartition('/')[0]
sys.path.append(pythonpath)
import config_common
import pan.config_mirror as config_mirror
SYSLOG_TO_FLOWS_LATENCY = 3
NUM_STATIC_FLOWS = 1
IP1 = '1.1.1.1'
IP2 = '2.2.2.2'
TCP = 6
UDP = 17
ICMP = 1
IP_PO... |
import cv2
import numpy as np
from sklearn.cluster import MiniBatchKMeans
import SimpleCV
class DepthTrackerManager(object):
def __init__(self):
self._disparity_map = None
self._left_image = None
self._right_image = None
@property
def disparity_map(self):
rgb_disparity_fr... |
import re
import copy
import math
import datetime as dt
import json
def decimalDate(date,fmt="%Y-%m-%d",variable=False,dateSplitter='-'):
""" Converts calendar dates in specified format to decimal date. """
if variable==True: ## if date is variable - extract what is available
dateL=len(date.sp... |
"""Main class for the Crownstone cloud cloud."""
import logging
import asyncio
import aiohttp
from typing import Optional
from crownstone_cloud.helpers.conversion import password_to_hash
from crownstone_cloud.cloud_models.crownstones import Crownstone
from crownstone_cloud.cloud_models.spheres import Spheres
from crown... |
# MIT License
#
# Copyright (c) 2021 willfuks
#
# 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 without limitation the rights
# to use, copy, modify, merge, pub... |
#
# PySNMP MIB module INTELCORPORATIONBASEBOARDMAPPER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATIONBASEBOARDMAPPER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:43:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... |
student = ("dora", 10, 110.5) # Student tuple with name, age, height
print("student", student)
print("name", student[0], "age", student[1], "height", student[2]) # access elements in the tuple
print("Number of elements in the tuple", len(student))
# Iterate thru items tuple
for item in student:
print(item)... |
import starfile
import eulerangles
import numpy as np
import pandas as pd
def star2pose(star_file):
star = starfile.read(star_file)
positions = star['particles'][[f'rlnCoordinate{ax}' for ax in 'XYZ']] \
.to_numpy()
shifts_angstroms = star['particles'][[f'rlnOrigin{ax}Angst' for ax in
... |
"""
Codemonk link: https://www.hackerearth.com/practice/data-structures/trees/binary-search-tree/practice-problems/algorithm/distinct-count/
Given an array A of N integers, classify it as being Good Bad or Average. It is called Good, if it contains exactly X
distinct integers, Bad if it contains less than X distinct i... |
import os
import argparse
from sys import platform
import cv2
from yolov3_depth.models import *
from yolov3_depth.utils.datasets import *
from yolov3_depth.utils.utils import *
from yolov3_depth.utils.parse_config import *
class Detector(object):
def __init__(self, opt):
self.opt = opt
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
__license__ = """
This file is part of GNU FreeFont.
GNU FreeFont is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, ... |
#!flask/bin/python
###############################################################################
# Training Service
# Handles requests for training sessions
#
# Copyright (c) 2017-2019 Joshua Burt
###############################################################################
#####################################... |
import random
import unittest
import igraph
from circulo.metrics import VertexCoverMetric
class TestMetrics(unittest.TestCase):
def setUp(self):
self.G=igraph.load("karate.gml")
membership=[
[0,1,2,3,7,11,12,13,17,19,21],
[4,5,6,10,16],
... |
#!/usr/bin/env python
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import matplotlib.pyplot as plt
import my_layers
def plot_sample(imgs_g):
for i in range(25):
plt.subplot(5, 5, i+1)
plt.imshow(imgs_g[i])
plt.tick_params(bottom=False, left=False, labelbotto... |
import datetime
import json
import os
import pandas as pd
from params import *
import requests
url_api = 'https://www.data.gouv.fr/api/1/datasets/5e5d89c28b4c410f100c3242/resources/'
resource_XLSX = '352b3cea-21d7-4cfc-87d3-dddab11b4021'
resource_CSV = 'bab27c3e-5620-47b2-8ed8-797c8192d905'
efs_collection = 'https:/... |
from tcf_connector.worker_registry_jrpc_impl import WorkerRegistryJRPCImpl
import logging
import unittest
import toml
from os import path, environ
import errno
import secrets
import json
from utils.tcf_types import WorkerType, WorkerStatus
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=... |
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from pyramid.renderers import JSONP
class GeoJSON(JSONP):
def __call__(self, info):
def _render(value, system):
request = system.get('request')
# Response should have appropri... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import ignite
def pixelwise_accuracy(num_classes, output_transform=lambda x: x, device=None):
"""Calculates class accuracy
Args:
num_classes (int): number of classes
output_transform (callable, optional): a... |
import json
import re
import scrapy
from locations.items import GeojsonPointItem
class StateFarmSpider(scrapy.Spider):
name = "statefarm"
item_attributes = { 'brand': "State Farm" }
allowed_domains = ["statefarm.com"]
download_delay = 0.2
start_urls = [
'https://www.statefarm.com/agent/u... |
import getpass
try:
p=getpass.getpass()
except Exception as err:
print('ERROR', err)
else:
print('You Enter', p) |
# -*- coding: utf-8 -*-
import sys
import re
import requests
import netaddr
import json
from collections import OrderedDict
from ipamcli.libs.phpipam import exception
VLANS = {'22': {'name': 'smev-vipnet-vlan', 'prefix': '10.32.250.0/24'},
'23': {'name': 'uek-vlan', 'prefix': '10.38.33.72/29'},
'24':... |
import os
# Playing music on mac will not work
mac = False
# os.name == "posix"
|
import amass
class Command(amass.commands.Command):
is_command = False
def __init__(self):
amass.commands.Command.__init__(self)
self.file = __file__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.