content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
"""
BluetoothMotors.py: Use bluetooth controller to control rover motors.
"""
__author__ = "Murray Ireland"
__email__ = "murray@murrayire.land"
__date__ = "16/01/2017"
import BluetoothController, time
from rrb3 import *
import numpy as np
# Initialise bluetooth controller
joystick = Blue... | python |
np.kron(np.eye(2), np.ones((2,2))) | python |
_MIN_TWO_DIGIT_HEX: int = 0x00
_MAX_TWO_DIGIT_HEX: int = 0xFF
def calculate_hex_digit(num: int) -> str:
if num < _MIN_TWO_DIGIT_HEX or num > _MAX_TWO_DIGIT_HEX:
raise RuntimeError('num is invalid and can not convert hex')
return hex(num)[2:].upper()
def calculate_opacity(percent_float: float) -> str... | python |
# -*- coding: utf-8 -*-
"""
Implements decorators used to retrieve and validate users/projects/teams/organizations/etc.
"""
from __future__ import unicode_literals
from __future__ import print_function
import re
from functools import wraps
from flask import request, jsonify
from collections import Sequence
f... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of pvsim.
# https://github.com/scorphus/pvism
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2017, Pablo Santiago Blum de Aguiar <pablo.aguiar@gmail.com>
import logging
import pika
class Broker(obj... | python |
# -*- coding: utf-8 -*-
from model.person import Person
import pytest
import random
import string
def test_add_contact(app):
contact = Person(firstname=app.session.get_random_string(), lastname=app.session.get_random_string(), company=app.session.get_random_string(),
ad... | python |
import os
def read_file(path):
lines = []
with open(path, "r", encoding="utf-8") as f:
lines = f.readlines()
lines = [ln.strip(os.linesep) for ln in lines]
return lines
def write_file(path, rows, separator="\t"):
with open(path, "wb") as outfile:
for row in rows:
... | python |
# Homework Header as usual
#
#
#
import sys
import doctest
def read_FASTA(fname):
""" (str) -> (list of tuples)
# function body with documentation
"""
return sequences # a list of (sequence_name , sequence) tuples
def identify_orfs(dnaStrand):
""" (str) -> (list of strings)
# function body with documentation... | python |
import numpy as np
import KalmanFilter as kf
from estimateSpeed import estimate_speed
class ObjectDetected:
def __init__(self, object_id, frame_number, indexes, H, pixelToMeters):
self.object_id = object_id
self.indexes = indexes
self.current_frame = frame_number
self.frames = [sel... | python |
#!/usr/bin/env python
# encoding: utf-8
########################################################################
#
# Copyright (c) 2016 Baidu, 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... | python |
import json
from typing import Optional
import dgeq
from channels.db import database_sync_to_async
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import Http404, JsonResponse
from pl_core.async_db import has_perm_async
from pl_core.enums import ErrorCode
from pl_core.mixins impo... | python |
# -*- coding: utf-8 -*-
import sys
import os
import json
import yaml
import string
import random
import shlex
import subprocess
from traceback import format_exc
from flask import Flask, request, jsonify
app = Flask(__name__)
app.url_map.strict_slashes = False
assert 'APP_ROOT' in os.environ, 'No APP_ROOT env variable... | python |
# Generated by Django 3.0.11 on 2020-12-17 13:49
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | python |
import numpy as np
def rle_to_mask(lre, shape=(1600, 256)):
'''
params: rle - run-length encoding string (pairs of start & length of encoding)
shape - (width,height) of numpy array to return
returns: numpy array with dimensions of shape parameter
'''
# the incoming string is ... | python |
import pygame, random
#Initialize pygame
pygame.init()
#Set display surface
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Group Collide!")
#Set FPS and clock
FPS = 60
clock = pygame.time.Clock()
#Define Classes
class Game(... | python |
# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
def get_time(num=0, sf="%Y%m%d",unit="days"):
'''
得到时间字符串
:param num: 和unit配合使用计算时间
:param sf: %Y%m%d%H%M%S
:param unit: days = None, seconds = None, microseconds = None, milliseconds = None, minutes = None, hours = None, weeks = None... | python |
from mutations.translator import TranslateSchema
| python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk... | python |
import configparser
import logging
from os.path import isfile
from typing import Dict, Union
import humanfriendly # type: ignore
from . import path_config
logger = logging.getLogger(__name__)
class GeneralClass:
def __init__(self, config: str = path_config.config_path_file) -> None:
if isfile(config):... | python |
"""
Tests for Office Model
"""
from unittest import TestCase
from app.api.v1.models.office import PoliticalOffice
class TestOfficeModel(TestCase):
"""
TestOfficeModel class
"""
def test_political_office_create(self):
"""
Test that PoliticalOffice Model Creates Political Offices
"""
political... | python |
"""Functions for getting current server resource use."""
from typing import Optional, Union
import psutil
import pandas as pd
import logging
import asyncio
import datetime
import numpy as np
import platform
import socket
import subprocess
from pathlib import Path
async def sample_resource_usage(data_dir: Path, file... | python |
# Extraindo dados de um arquivo CSV e exibindo com Matplotlib
import csv
from matplotlib import pyplot as plt
from exe1600_country_codes import get_country_code
# Obtém as datas e as temperaturas máximas e mínimas do arquivo
# filename = 'sitka_weather_07-2014.csv'
# filename = 'sitka_weather_2014.csv'
filename = 'd... | python |
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from renormalizer.mps import Mps, Mpo
from renormalizer.model import MolList2, ModelTranslator
from renormalizer.utils.basis import BasisSHO, BasisMultiElectronVac, BasisMultiElectron, BasisSimpleElectron, Op
from renormalizer.tests import parameter
@pytest.m... | python |
# Generated by Django 3.2.6 on 2021-08-10 11:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdressEntery',
fields=[
... | python |
# -*- coding: utf-8 -*-
""" LSOF class, a parallelized class for processing lsof output into a dict
Copyright (C) 2017 copyright /at/ mzpqnxow.com under the MIT license
Please see COPYRIGHT for terms
"""
from __future__ import print_function
from collections import defaultdict
from proclib.worker import ProcToolWorker... | python |
"""
This script creates plots to visualize the results of simulations of the differential growth model.
Later on, it will also be used to visualize other models that work with discrete systems.
This script starts by importing a csv file of the results, creates a plot, shows it, and then exports it as a png to the same... | python |
'''
(c) University of Liverpool 2019
All rights reserved.
@author: neilswainston
'''
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
# pylint: disable=wrong-import-order
import os
import shutil
import sys
import pandas as pd
from synbiochem.utils import ice_utils... | python |
"""
Script to restore subject information from the HANDS 2017 training set. It is known that each sample
in the dataset belongs to one out of 5 subjects. It can be assumed that each subject has a slightly
different hand shape. By running a simple clustering algorithm on the bone lengths the mapping from
subjects to sam... | python |
import click
import random, string
import decimal
import datetime
import names
from flask.cli import FlaskGroup
from src.app import create_app
from src.models import db, User, Computer, PurchaseDetails, Accounts
@click.group(cls=FlaskGroup, create_app=create_app)
def cli():
pass
def create_db():
db.drop_all... | python |
import heapq
from dataclasses import dataclass, field
from operator import lt
from typing import Dict, List, Optional, Tuple
# default collection name if none is specified.
DEFAULT_COLLECTION_NAME = "default_collection"
"""
Time Taken By Me -> 33 mins 18 secs
Atlassian LLD Round -:
Design the following -:
... | python |
#!/usr/bin/env python
from EPPs.common import StepEPP
class AssignNextStepSampleReceipt(StepEPP):
"""
This script checks to see if any of the relevant step UDFs are answered indicating that a manager review is required
"""
def _run(self):
# obtain the actions of the step then creates a StepA... | python |
import json
import domoticz
import configuration
from adapters import adapter_by_model
from zigbee_message import ZigbeeMessage
from adapter import UniversalAdapter
class DevicesManager:
def __init__(self):
self.devices = {}
def set_devices(self, zigbee_devices):
self.devices = {}
for... | python |
try:
total
except:
ffin dyh | python |
#!/usr/bin/env python
import gzip
import os
import sys
from parseExternalDatabase import *
from RNAIsoformAnnotator import *
from RNAIsoform import RNAIsoform
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
import pysam
import pybedtools
# Do this in main and put on command line
pybedtools.set_bedtools_path("... | python |
# -*- coding: utf-8 -*-
"""Fixture to keep legacy unit tests working."""
from tackle import models
def update_source_fixtures(
template,
abbreviations,
clone_to_dir,
checkout,
no_input,
password=None,
directory=None,
):
"""Mock the old cookiecutter interfece for tests."""
source =... | python |
from Jumpscale import j
import pytest
def main(self):
"""
to run:
kosmos 'j.data.schema.test(name="unittests")' --debug
"""
return
unittests_path = "/sandbox/code/github/threefoldtech/jumpscaleX/Jumpscale/data/schema/tests/testsuite"
assert pytest.main([unittests_path]) == 0
| python |
'''
Author: Hans Erik Heggem
Email: hans.erik.heggem@gmail.com
Project: Master's Thesis - Autonomous Inspection Of Wind Blades
Repository: Master's Thesis - CV (Computer Vision)
'''
import glob, warnings, os
'''
@brief Class for getting test sets
Change data sets as preferred to use for testing.
'''
class Test... | python |
/usr/lib/python2.7/encodings/iso8859_8.py | python |
"""genericPlots.py
Plots that require matplotlib (but not plotly)
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def publisher_histogram(df, title, ylabel):
"""
A specifically selected dataframe.
From df->clean_df->pyblishers
Plot a histogram showing the distribution
... | python |
import logging
import requirements
logger = logging.getLogger(__name__)
EXCLUDE_REQUIREMENTS = frozenset((
# obviously already satisfied or unwanted
'ansible', 'ansible-base', 'python', 'ansible-core',
# general python test requirements
'tox', 'pycodestyle', 'yamllint', 'pylint',
'flake8', 'pytes... | python |
#
# Copyright 2014 Thomas Rabaix <thomas.rabaix@gmail.com>
#
# 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... | python |
from . import models
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserCreateForm(UserCreationForm):
class Meta(UserCreationForm):
model = get_user_model()
fields = ("email",)
class Cust... | python |
from __future__ import unicode_literals
import frappe
import json
import pyqrcode
from PIL import Image, ImageDraw
import io
import requests
import base64
import textwrap
import re
@frappe.whitelist()
def check_stock(doc,method):
if doc.get('__islocal')!= 1:
final_item_status = []
final_item_percent = []
ohs = ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 EMBL - European Bioinformatics 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.apache.org/licenses/LICEN... | python |
import re
from zen_document_parser.base import DocField, DocVariant
from zen_document_parser.exceptions import FieldParseError
class ITRVBase(DocVariant):
# Overridden in subclasses
for_year = None
test_fields = ['form_title', 'assessment_year']
form_title = DocField((52, 745, 478, 774))
# Fo... | python |
import FWCore.ParameterSet.Config as cms
from Validation.RecoTrack.TrackingParticleSelectionsForEfficiency_cff import *
from Validation.RecoTrack.GenParticleSelectionsForEfficiency_cff import *
MTVHistoProducerAlgoForTrackerBlock = cms.PSet(
### tp selectors for efficiency
generalTpSelector = gener... | python |
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from django.core.exceptions import ObjectDoesNotExist
import tastypie.http as http
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from... | python |
"""
Copyright (c) 2019, NVIDIA CORPORATION. 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 list of conditions and the fo... | python |
from .bases import AuditBackend
class SyslogBackend(AuditBackend):
"""The `syslog` audit backend writes audit logs to syslog.
"""
def validate(self, *, facility='AUTH', tag='vault', log_raw=False):
"""Configure audit backend.
Parameters:
facility (str): The syslog facility to... | python |
import numpy as np
from scipy.linalg import svd
__all__ = ['orthomax']
def orthomax(Phi, gamma=1., maxiter=20, tol=1e-6):
"""
Given n*k factor matrix Phi (k number of factors, n number of dimensions),
find a rotated version of the factor loadings that fulfills optimization criteria,
depending on gamm... | python |
import json
import time
from threading import Thread
from typing import Any, Dict, List
from uuid import uuid4
import pytest
import redis
from confluent_kafka import OFFSET_END, Consumer, Producer, TopicPartition
from rsmq import RedisSMQ
from example.data_models import InputMessage
from example.kafka_kafka_worker im... | python |
from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
str = type('')
import io
import warnings
from collections import defaultdict
from threading import Lock
try:
from spidev import SpiDev
except ImportError:
SpiDev = None
from . import SPI
from .pi impor... | python |
# Generated by Django 3.0.3 on 2020-02-25 12:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='srtmodel',
name='srt',
field=... | python |
# Cogs to enable on Starting
__cogs__ = ['cogs.admin',
'cogs.anime',
'cogs.fun',
'cogs.information'
#'cogs.utilities'
] | python |
from flask import Flask, request, jsonify, render_template
from flask_socketio import SocketIO, emit
from flask_classful import FlaskView, route
import time
class Server(Flask):
_config = None
state = None
socketio = None
last_timestamp = None
connected = False
def __init__(self, config):
... | python |
"""Serializers module."""
from rest_framework import serializers
from django_celery_results.models import TaskResult
from api import models
class ExchangeSerializer(serializers.ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
class Meta:
"""Meta class to map serializer'... | python |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
"""
@project: occurrence-abundance pattern (parameters for Fig 5A - source code)
@author: Roman Zapien-Campos - 2021
"""
# Import packages
import numpy as np
### Define parameters ###
# General parameters
# Number of microbes within a host
N = 1E3
# Number of micr... | python |
#
# Copyright 2013-2020 University of Southern California
#
# 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... | python |
import requests
import os
SERVER = 'http://127.0.0.1:8000/'
PAGE_1 = 'api/1.0.0/doctor/'
PAGE_2 = 'api/1.0.0/title/'
AUTH = ('SU', 'superuser',)
response = requests.get(os.path.join(SERVER, PAGE_1))
print(response.text)
response = requests.get(os.path.join(SERVER, PAGE_2))
print(response.text)
response = requests.d... | python |
"""
Project Euler - Problem Solution 037
Problem Title - Truncatable primes
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def truncated_nums(prime):
''' Generates every truncation of a number. '''
digits = str(prime)
for i in range(1, len(digits... | python |
import logging
import sys
from time import sleep
import pigpio
from errors import I2CReadError, I2CWriteError
from .i2c_driver import I2cDriver
class SdpPressureSensor(I2cDriver):
"""Driver class for SDP8XXX Pressure sensor."""
I2C_ADDRESS = 0x25
MEASURE_BYTE_COUNT = 0x3
CMD_TRIGGERED_DIFFERENTIAL_P... | python |
from flask import Flask, url_for, request, render_template
import numpy as np
import csv
import math
app = Flask(__name__)
def compute_ln_norm_distance(vector1, vector2, n):
vector_len = len(vector1)
distance = 0
for i in range(vector_len):
distance += (abs(vector1[i] - vector2[i])) ** n
... | python |
from bank_account import BankAccount
joes_account = BankAccount(500)
print(joes_account.get_balance())
print()
joes_account.deposit(500)
print(joes_account.get_balance())
print()
joes_account.withdraw(100)
print(joes_account.get_balance())
| python |
import sys
import matplotlib
import numpy as np
# Avoid errors when running on headless servers.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
sys.path.insert(0, '/root/jcw78/process_pcap_traces/')
import graph_utils
if len(sys.argv) < 7:
print "Usage plot.py <min rate> <step size> <max rate> <num packets ... | python |
def load(path):
with open(path) as f:
content = f.read()
return hig(d)
def parsetodict(content):
"""
:type content: str
:param content:
:return:
"""
if '=' in content:
content.partition('=')
#takes string and writes in hig format
def dict2str(d, depth=0):
content... | python |
'''
For your reference:
class TreeNode:
def __init__(self, node_value):
self.val = node_value
self.left_ptr = None
self.right_ptr = None
'''
def kth_smallest_element(root, k):
def traverse(node, index):
if not node:
return None
left_result = tra... | python |
class ImageJ_RelaxationTime_profil():
def __init__(self,
image='path',
relax_Time='path',
Intensity='path',
Shift='path',
ListTime=[0.0],
time_type="enumerate(('EchoTime',\
'... | python |
'''
Session 07
Timing helper class
'''
import time
class Stopwatch:
def __init__(self, nanoseconds=False):
self.timefunc = time.perf_counter_ns if nanoseconds else time.perf_counter
self.reset()
def elapsed(self):
return self.timefunc() - self.tic
def reset(self):
self... | python |
#!/usr/bin/python
import zipfile
with zipfile.ZipFile('subor.zip', 'r') as zf:
print(zf.namelist())
| python |
import time
from web3 import Web3, HTTPProvider
abi = '''
[
{
"constant": false,
"inputs": [
{
"name": "target",
"type": "uint256"
}
],
"name": "bump",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
... | python |
#encoding:utf-8
subreddit = 'Trackers'
t_channel = '@r_trackers'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| python |
import sys
import argparse
import re
from selenium import webdriver
from selenium.webdriver.chrome import service as cs
from selenium.webdriver.common.keys import Keys as keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriv... | python |
# !/uer/bin/env python3
"""
@author: Medivh Xu
@file: db_manager.py
@time: 2020-02-27 12:22
"""
import pymysql
import contextlib
from loguru import logger
from config_loader import conf_load
@contextlib.contextmanager
def mysql(filename=None, **conf):
"""
mysql连接方法
examples:
:type(env... | python |
#!/usr/bin/env python3
# test/calib.py
import enum
import matplotlib.pyplot as plt
import logging
import numpy as np
import os, sys
from astropy.io import fits
from scipy.ndimage import median_filter
from pyFU.utils import check_directories, construct_new_path, get_sec, get_list_of_paths_and_filenames, get_in... | python |
"""This module implements the Choices system for user preferences.
The environment variable CHOICESPATH gives a list of directories to search
for choices. Changed choices are saved back to the first directory in the
list."""
import os
from os.path import exists
try:
path = os.environ['CHOICESPATH']
paths = path.spl... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... | python |
# python
from chempy import io
from chempy import protein
from chempy import protein_amber99
model= io.pdb.fromFile("../../test/dat/pept.pdb")
model= protein.generate(model,forcefield=protein_amber99)
sm = 0
for a in model.atom:
sm = sm + a.partial_charge
print(" prot: net partial charge on protein is %8.4f" % ... | python |
import numpy as np
from pyrfsim import RfSimulator
import argparse
from scipy.signal import gausspulse
from time import time
description="""
Demo program showing how to use the fixed-scatterer GPU
implementation from Python.
Also useful to measure the running time of the GPU
implementations.
"""
... | python |
import asyncio as aio
import logging
import random
import re
from datetime import datetime, timedelta
from aiogram import types, Bot
from aiogram.utils import markdown as md
from aiogram.utils.exceptions import *
from aiochatbase import Chatbase
from antiflood import rate_limit
from languages import underscore as _
f... | python |
from django.contrib import admin
from .models import Arts, Comments, Tags, ArtworksTags, Stili, Umetnina, Umetnik
# Register your models here.
admin.site.register(Umetnik)
admin.site.register(Umetnina)
admin.site.register(Stili)
admin.site.register(Arts)
admin.site.register(Comments)
admin.site.register(Tags)
admin.... | python |
from stencil_ir import *
from verify import *
from assertion_to_sketch import *
import asp.codegen.ast_tools as ast_tools
from invariant import *
import logging
def loop_key(node):
import hashlib
return hashlib.sha224(tree_to_str(node)).hexdigest()[0:10]
class RHSInvariantReplacer(ast_tools.NodeTransformer):
... | python |
class Job():
def __init__(self):
self.using = False
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setDisplayName(self, dname):
self.dname = dname
def getDisplayName(self):
return self.dname
def IamWerewolf(self, we... | python |
import sys
import numpy as np
import pandas as pd
from sys import argv, __stdout__
from datetime import datetime, timedelta
import os
### This program makes a timing dataframe from output logfiles generated by graphB.
### It can take multiple files as command line arguments manually, in which it will generate
### one... | python |
import os, sys, socket, urlparse
###
class socket_uri(object):
'''
Socket factory that is configured using socket URI.
This is actually quite generic implementation - not specific to console-server IPC communication.
'''
# Configure urlparse
if 'unix' not in urlparse.uses_query: urlparse.uses_query.append('uni... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import json
import traceback
import re
from optparse import OptionParser
from couchdbkit import Server, ChangesStream
from pywebhdfs.webhdfs import PyWebHdfsClient
from ConfigParser import ConfigParser
#we make ample use of these docs.
#pywebdfs: http://p... | python |
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | python |
#
# PySNMP MIB module BGP4-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BGP4-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:18:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | python |
from _animation import get_joint_transform_from_rig
from _math import Vector3, Quaternion
from routing import SurfaceIdentifier, SurfaceType, Location
from sims4.math import angle_to_yaw_quaternion
from sims4.tuning.geometric import TunableVector2
from sims4.tuning.tunable import HasTunableFactory, OptionalTunable, Tun... | python |
#!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# 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,... | python |
from random import randint
class Node:
def __init__(self,value = None):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return str(self.value)
class linkedList:
def __init__(self):
self.head = None
self.tail = None
def __i... | python |
import socket, sys, ssl, uuid, thread, json, re
from functools import partial
class Susi:
def __init__(self,addr,port,cert,key):
s = None
for res in socket.getaddrinfo(addr, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
... | python |
import os
import logging
from twisted.python.failure import Failure
from scrapy.utils.request import referer_str
SCRAPEDMSG = "Scraped from %(src)s" + os.linesep + "%(item)s"
DROPPEDMSG = "Dropped: %(exception)s" + os.linesep + "%(item)s"
CRAWLEDMSG = "Crawled (%(status)s) %(request)s%(request_flags)s (referer: %(re... | python |
import numpy as np
from webdnn.graph.graph import Graph
from webdnn.graph.order import OrderNCHW
from webdnn.graph.variable import Variable
from webdnn.graph.variables.constant_variable import ConstantVariable
from webdnn.optimizer.sub_rules.simplify_commutative_operator import SimplifyCommutativeOperator
def test_s... | python |
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import numpy as np
import socket
def initializeSocket():
host, port = "127.0.0.1", 25001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))
return sock
def initializeCircuit():
c... | python |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from timm.models.vision_transformer import _cfg, PatchEmbed
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, ... | python |
#!/bin/usr/env python
import argparse
import requests
import json
def parse_args():
parser = argparse.ArgumentParser(description='')
parser.add_argument(
'--type',
'-t',
action='store',
choices=[
'hour',
'day',
'week',
'month',
... | python |
import pandas as pd
import numpy as np
def load_chart_data(fpath):
chart_data = pd.read_csv(fpath, thousands=',', header=None)
chart_data.columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'action_B', 'action_H', 'action_S']
return chart_data
def preprocess(chart_data):
prep_dat... | python |
from CommandManager import CommandManager
from Command import Command
from ActionManager import ActionManager
from Action import Action
import json
import cv2
#class voor de load
class Load(object):
actionManager = ActionManager()
def loadActions(self): #loads ... | python |
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Button:
__metaclass__ = ABCMeta
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in linux style"
class WindowsButton(Button):
def paint(... | python |
"""Benchmark task for testing constraint satisfaction with sphere."""
import sympy
from sympais import distributions as dist
from . import base
class Sphere(base.Task):
"""Task for constraint satisfaction with spheres."""
def __init__(self, nd: int):
"""Construct a `Sphere` task.
Args:
nd: number... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.