content stringlengths 5 1.05M |
|---|
import pytest
import fast_carpenter.define.variables as fast_vars
@pytest.fixture
def variable_simple():
define = "sqrt(MET_px**2 + MET_py**2)"
return define
@pytest.fixture
def variable_jagged():
define = dict(formula="sqrt(Electron_Px**2 + Electron_Py**2)")
return define
@pytest.fixture
def vari... |
from math import sqrt
class ColorCube:
def __init__(self, color1, color2, using_delta=False):
if (not using_delta and color1[0] < 0 or
color1[0] >= 360 or color1[1] < 0 or
color1[1] > 100 or color1[2] < 0 or
color1[2] > 100 or color2[0] < 0 or
color2[0] >= 360... |
from sharptable.tables.matplotlib_table import MatplotlibTable
from sharptable.tables.table import Table
|
# Generated by Django 2.2.1 on 2019-07-01 16:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ptart', '0003_project_conclusion'),
]
operations = [
migrations.AddField(
model_name='screenshot',
name='caption',
... |
#Created by SharkBaitBilly
#https://github.com/ajsya/ServerAlerter
import time
import requests
from mcstatus import MinecraftServer
from pynput.mouse import Button, Controller
# Settings
SendDiscordMessage = False #Send a discord message when server open (True/False)
DiscordWebhookURL = "" #Set a webhook url for the ... |
from datetime import datetime
# Defines the authentication models.
from ..database import db
"""
User model
Version: v0.0.1
"""
class users_administration(db.Model):
__tablename__ = "users_administration"
id = db.Column('user_id', db.Integer , primary_key=True)
username = db.Column('username', db.String(... |
__all__ = ['RF2Files', 'OWLGraphHelper', 'SNOMEDToOWLConstants', 'TransformationContext']
|
from django.shortcuts import render_to_response
def home(request):
return render_to_response('demo.html')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##===-----------------------------------------------------------------------------*- Python -*-===##
##
## S E R I A L B O X
##
## This file is distributed under terms of BSD license.
## See LICENSE.txt for more information.
##
##===-------... |
import requests, json
#api_key = None
URL = 'https://api.tensorbox.ai'
class Client:
api_key = None
@classmethod
def set_api_key(cls, key):
cls.api_key = key
@classmethod
def generate(cls, payload):
api_key = cls.api_key
if api_key == None:
raise Exception("API ... |
"""
option_types.py
Copyright 2008 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 version 2 of the License.
w3af is distributed in the hope tha... |
# Copyright (c) 2021 K.M Ahnaf Zamil
# 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, publish, dist... |
# -*- coding: utf-8 -*-
"""CLI for alignment."""
import click
from .biolink import BiolinkAligner
from .bioportal import BioPortalAligner
from .go import GoAligner
from .miriam import MiriamAligner
from .n2t import N2TAligner
from .ncbi import NcbiAligner
from .obofoundry import OBOFoundryAligner
from .ols import OL... |
#!/usr/bin/python
l = range(0, 10)
# NEW!
# "List comprehensions".
# Read as in English:
# "Generate a list of x*x for each x in l".
squares = [x*x for x in l]
print "Squares of l:\n %s" % squares
# "Generate a list of x*x for each x in l which is odd".
odd_squares = [x*x for x in l if x % 2 == 1]
print "Squares o... |
__strict__ = True
from crawlers.base import client_fetch
from models.model import Player
async def find_user_id(name: str) -> str:
result = await client_fetch("/ISteamUser/ResolveVanityURL/v1/", {"vanityurl": name})
response = result["response"]
if response["success"] != 1:
raise ValueError(respo... |
import pytest
from string import ascii_lowercase
from django.urls import reverse
from django.test import TestCase
from faker import Faker
from hypothesis import given, settings
from hypothesis.extra.django import TestCase as HTestCase
from hypothesis.strategies import characters, integers, floats
from rest_framewor... |
# Generated by Django 3.1.5 on 2021-04-25 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0003_author_author_image'),
]
operations = [
migrations.AddField(
model_name='author',
name='email',
... |
import utils
import threading
from time import sleep
UPDATE_FIFO = 0.05
UPDATE_BUFFER = 0.2
AUTO_SAVE = 20
class Database:
def __init__(self, database_file, check_dup = True):
self.buffer = []
self.buffered_fifo = []
self.fifo = []
self.database_file = database_file
self.chk_du = check_dup
... |
#!/usr/bin/env python
import unittest
import os
from lib.plan import plan_index, plan_filepath
from test.lib.corrigible_test import CorrigibleTest
import lib.plan
script_dirpath = os.path.join(os.path.dirname(lib.plan.__file__), '..', 'test')
system_config_dirpath = os.path.join(script_dirpath,'resources','systems'... |
#!/usr/bin/python
import pyNetIO as lower_IO
import time
from General_tools import *
SCALA_root = "/home/scala1/SCALA/"
INPUT_data = SCALA_root+"SCALA_library/INPUTS/"
#########################
# --------------------- #
# - TEST & CONNEXION - #
# --------------------- #
#########################
def Status_Test(Bo... |
import moves as m
import board
def pawn_check(array_location, end_array_location, available_moves, boardstate) -> bool:
"""
A function that checks if a pawn move is possible
"""
for move in available_moves:
if array_location + (m.whos_move * move) == end_array_location:
#Checks if ... |
from tkinter import *
root = Tk()
height = 5
width = 6
textv = StringVar()
b1 = Entry(root, textvariable=textv).grid(row=7, column=0)
for i in range(height): #Rows
for j in range(width): #Columns
b = Entry(root, textvariable=textv)
b.grid(row=i, column=j)
mainloop() |
"""
Case 2
Primary Monitoring module has required a view change at 3f+1 nodes,
node 5 does not want to change view.
Node 0-4 should conduct the view change, node 5 should eventually follow
to the new view (2,2).
"""
# standard
import asyncio
import logging
from copy import deepcopy
# local
from . import helpers
fr... |
def main(string, count = 1, separator = ""):
try:
if count > len(string): return None
index = len(string) - count
output = string[index:len(string)] + separator + string[0:index]
return output
except: return None
|
from flask import Blueprint, render_template
from .forms import LoginForm
bp = Blueprint('hotel', __name__)
@bp.route('/', methods=['GET'])
@bp.route('/home', methods=['GET'])
def home():
form = LoginForm()
return render_template('hotel/home.html', form=form)
|
#!/usr/bin/env python3
from pwn import *
# ASLR, PIE, CANARY, NX
context.update(arch='amd64', os='linux') # set arch
#context.terminal = ['mate-terminal', '-e'] # set terminal
p = process('./9teaching1')
# n in the stack, so, we can overwrite n with a arbitrary value and write past
# the canary token
# while (n < ... |
import _pickle as pickle
from datetime import datetime
import torch
import bcolz
import jsonpickle
import numpy as np
from jsonpickle.ext import numpy as jsonpickle_numpy
jsonpickle_numpy.register_handlers()
def get_idx(genre, le):
class_idx = np.where(le.classes_ == genre)[0]
if len(class_idx) == 0:
... |
print("Matt is Gay")
num1 = input("PLease enter your first number")
print(num1)
num2 = input("PLease enter your first number")
print(num2)
num3 = input("PLease enter your first number")
print(num3)
#work out the biggest number.
if num2 < num1:
print("Number One is bigger than number two")
if num1 > num3:
... |
# Copyright The OpenTelemetry 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 ... |
import requests
import json
import xlwt
from tempfile import TemporaryFile
import pandas as pd
import re
import translators as ts
column = list()
one = list()
one_rus = list()
two = list()
three = list()
four = list()
start=27
bolt = pd.read_csv('bolt-ev.csv', index_col=0)
pd.options.display.max_colwidth = 10000
d... |
# Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# 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, ... |
__version__ = '0.1.33'
from .gdal import GeoInfo, RasterDataset, Resampling, VectorDataset
from .options import *
|
from djangobench.utils import run_benchmark
def setup():
global Book
from query_iterator.models import Book
def benchmark():
global Book
list(Book.objects.iterator())
run_benchmark(
benchmark,
setup=setup,
meta={
'description': 'A simple Model.objects.iterator() call.',
}
)
|
from server.domain.common.pagination import Page, Pagination
from server.domain.common.types import ID
from server.domain.datasets.specifications import DatasetSpec
from server.seedwork.application.queries import Query
from .views import DatasetFiltersView, DatasetView
class GetAllDatasets(Query[Pagination[DatasetVi... |
from distutils.version import LooseVersion
__version__ = '0.1.2'
__version_info__ = tuple(LooseVersion(__version__).version)
from .cli import AssetCLI # noqa
from .manager import AssetManager # noqa
|
print("ENter number")
n = int(input())
for i in range(1, n+1):
print(i, end=" ")
# 1) pip install pyinstaller
# 2) add program file in folder
# 3) open power shell window in that folder
# 4) python (filename) enter tab
# 5) pyinstaller (file name)
# 6) open dist file and open (filename) file
# 7) go to powe... |
import argparse
import csv
import os
import subprocess
from os.path import isfile, join as join_path
tasks = {
"all": ["ESC07.sop", "ESC11.sop", "ESC12.sop", "ESC25.sop", "ESC47.sop", "ESC63.sop", "ESC78.sop", "br17.10.sop",
"br17.12.sop", "ft53.1.sop", "ft53.2.sop", "ft53.3.sop", "ft53.4.sop", "ft70.1... |
from django import forms
from .models import InterestedPerson
class EmailForm(forms.ModelForm):
# email = forms.EmailField(label='Email', max_length=100)
class Meta:
model = InterestedPerson
fields = ["email"] |
import yaml
import click
from pytuya.cli.main import cli_root, get_keys_from_file, build_config, config
from pytuya.utils import query_devices
@cli_root.group("utils")
def utils():
pass
@utils.command("extract_keys")
@click.argument('api_response_path', default=None, type=click.Path(file_okay=True, dir_okay=Fal... |
store.set_global_value('hotkey', '<super>+p')
engine.set_return_value('<up>')
engine.run_script('mapkeys')
|
from PIL import Image
import PIL
import torch
import torchvision.transforms.functional as F
import random
from mixup import parse_annot
def intersect(boxes1, boxes2):
'''
Find intersection of every box combination between two sets of box
boxes1: bounding boxes 1, a tensor of dimensions (n1, 4)
... |
# Generated by Django 3.2.8 on 2021-11-05 07:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vault', '0007_rename_pwd_keys_enc_pwd'),
]
operations = [
migrations.AlterField(
model_name='keys',
name='enc_pwd',
... |
#!/usr/bin/env python3
import os
import numpy as np
import pandas as pd
import networkx as nx
import random
import sfa
import csv
import sys
import statistics
fpath = os.path.join(sys.argv[1]) #location of networkfile
qdata_all=pd.read_csv(sys.argv[2],index_col = 0)
all_samples=pd.read_csv(sys.argv[3],delim_whites... |
l1 = float(input('Digite o comprimento do primeiro lado: '))
l2 = float(input('Digite o comprimento do segundo lado: '))
l3 = float(input('Digite o comprimento do terceiro lado: '))
if l1 > (l2 + l3) or l2 > (l1 + l3) or l3 > (l1 + l2):
print('Estes lados não formam um triângulo!')
else:
print('Estes lado... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, instance):
if request.user.is_superuser:
return True
return request.user.id == instance.user_id
|
import numpy as np
from ..action.action import Exploit
from .utils import SERVICES_TCP, REWARDS
class Network:
"""Collect of Hosts objects, with helper functions for comparing them
"""
def __init__(self, max_subnets, max_hosts_per_subnet):
self.hosts = []
self.max_subnets = max_subnets
... |
#!/usr/bin/env python3
__author__ = 'Mohamed Radwan'
from src.train import train_speed_data, train_direction_data
def main():
num_epochs=10
print('Speed Data...')
train_speed_data(num_epochs)
#print('Direction Data')
#train_direction_data(num_epochs)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is the visualization of correlations
"""
import os, pathlib
import numpy as np
from astropy.io import ascii
from scipy.optimize import curve_fit
from matplotlib.ticker import ScalarFormatter, NullFormatter
import matplotlib.colors as mcolors
## rapyuta
from ra... |
# A set of utilities for audio IO and essential handling
#
# Data Formats:
# audio data is passed as (float32) numpy arrays using the 'implicit mono' convention ( librosa)
# + (n_samples,_) for mono
# + (n_channels,n_samples) for multichannel data
#
# Alternatives:
# (i) PyTorchAudio uses Explicit mono with c... |
# Lint as: python3
# Copyright 2020 The TensorFlow 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 ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from distutils.spawn import find_executable
from distutils import sysconfig, log
import setuptools
import setuptools.command.build_py
import setuptools.command.develop
im... |
"""TODO: make this a phrasebook for turning XML -> python dictionaries and vice versa.
"""object OMOBJ
attribution OMATTR
attribution pairs OMATP
(symbol, string)+ OMS, OMSTR
application = function call OMA
symbol = function name
argument objects""" |
# -*- coding: utf-8 -*-
# Name: photons.py
# Authors: Stephan Meighen-Berger
# Calculates the number of photons depending on the track length
import logging
import numpy as np
from .config import config
from .tracks import Track
from .em_cascades import EM_Cascade
from .hadron_cascades import Hadron_Cascade
try:
i... |
import os
import numpy as np
from scipy.optimize import linear_sum_assignment
from ._base_metric import _BaseMetric
from .. import _timing
from .. import utils
# Global variables
fn_dataset = False
fp_dataset = False
idsw = False
class CLEAR(_BaseMetric):
"""Class which implements the CLEAR metrics"""
@sta... |
f = open('statiscit.txt', 'w')
ST_A = 0
ST_B = 0
ST_C = 0
f.write('hit_id'+' '+ 'all_different' + ' ' +'2 vs. 1' + ' '+ 'all the same')
for i in range(50):
st_a = 0
st_b = 0
st_c = 0
txt_name = 'output' + str(i) + '.txt'
txt = open(txt_name,'r')
lines = txt.readlines()
line_num = len(lines)... |
from sqlalchemy import Column, Integer, String, ForeignKey
from models.database import Base
class Student(Base):
__tablename__ = 'student'
id = Column(Integer, primary_key=True)
surname = Column(String)
name = Column(String)
patronymic = Column(String)
age = Column(Integer)
address = Col... |
#超分倍率
scale=2
#参数路径,可更换
model_path2 = "weights_v3/up2x-latest-denoise3x.pth"
model_path3 = "weights_v3/up3x-latest-denoise3x.pth"
model_path4 = "weights_v3/up4x-latest-denoise3x.pth"
#早期显卡开半精度不会提速,但是开半精度可以省显存。
half=True
#tile分为0~4一共5个mode。0在推理时不对图像进行切块,最占内存,mode越提升越省显存,但是可能会降低GPU利用率,降低推理速度
tile=2
#超图像设置
device="cuda... |
# By Kami Bigdely
"""
PEP8 - Refactor code by removing unnecessary whitespaces, adding docstrings,
and formalizing variable names.
"""
class pizza:
"""
Class for creating pizza objects
"""
def __init__ (self, bread_type, cheese_type, meat_type, pizza_toppings, size):
self.bread= bread_type
... |
import numpy as np
def polar2cart_2D(r, θ):
"""
Convert 2D polar coordinates to Cartesian coordinates.
"""
x = r * np.cos(θ)
y = r * np.sin(θ)
return x, y
def order_coplanar_points(points, normal, anticlockwise=True):
"""
Find the clockwise or anticlockwise ordering of a set of copl... |
############################################################################################
#
# Project: Peter Moss Acute Myeloid & Lymphoblastic Leukemia AI Research Project
# Repository: ALL Detection System 2019
# Project: Data Augmentation
#
# Author: Adam Milton-Barker (AdamMiltonBarker.com)... |
def digitsum(s):
total=0
for i in s:
total+=int(i)
return total
def chess_board_cell_color(cell1, cell2):
trans=str.maketrans("ABCDEFGH","12345678")
return digitsum(cell1.translate(trans))%2==digitsum(cell2.translate(trans))%2 |
"""
Afterglow Core: API v1 data file views
"""
import sys
import os
import astropy.io.fits as pyfits
import gzip
from io import BytesIO
from datetime import datetime
from typing import Optional, Union
import numpy
from flask import Response, request
from astropy.wcs import WCS
from .... import app, json_response, au... |
# 倒山峰形
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
ax = plt.axes(projection="3d")
x = y = np.arange(start=-4, stop=4, step=0.1)
X, Y = np.meshgrid(x, y)
Z = X**2+Y**2
ax.plot_surface(X,Y,Z,alpha=0.9, cstride=1, rstride = 1, cmap='rainbow')
plt.show()
exit()
#峰值函数上半轴
import numpy as np
f... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.topology import breadth_first_traverse
from compas.topology import connected_components
__all__ = [
'mesh_is_connected',
'mesh_connected_components'
]
def mesh_is_connected(mesh):
""... |
import serial
import time
class scpi_wrapper:
def __init__(self,port,baudrate=57600,bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,timeout=1):
ser = serial.Serial()
ser.port = port
ser.baudrate = baudrate
ser.bytesize = bytesize
ser.parity =... |
import re
import six
import types
import functools
import requests
from simplejson.decoder import JSONDecodeError
from flattrclient.exc import raise_exception
def _handle_response(resp, accepted_codes=[200], do_json=True):
if resp is None:
# If there is no response, most likely because no request happened,... |
import torch
from torch.nn import Parameter
from models import PaDiMBase
from utils.utils import get_embedding
class PaDiM(PaDiMBase):
def __init__(self, params: dict, backbone_params: dict, device):
super().__init__(params=params, backbone_params=backbone_params, device=device)
self.means = Pa... |
import os
import requests
import unittest
import pytest
DB_USER = os.environ.get("DB_USER")
DB_PASS = os.environ.get("DB_PASS")
DB_URL = os.environ.get("DB_URL")
DB_PORT = os.environ.get("DB_PORT")
WEATHERKEY = os.environ.get("WEATHERKEY")
station_lat =53.3498
station_lat =6.2603
# API Key for Dublin Bikes JCDecaux & ... |
import socket
import struct
import os
# import spidev
from multiprocessing import Process, Value, Array, Lock
from time import perf_counter
# TODO:
# Add support of python-can lib
# Add different hardware devices
# can-hacker
#
# Rename CAN_Bus - to CANSocket
# Implement the object with 5 virtual
# rPyCAN
#
cl... |
from litex.gen import *
from litex.soc.interconnect.csr import *
from litex.soc.cores.gpio import GPIOOut
from litex.gen import *
from litex.soc.interconnect.csr import *
class SPIMaster(Module, AutoCSR):
def __init__(self, pads, width=24, div=2, cpha=1):
self.pads = pads
self._ctrl = CSR()
... |
from django.contrib import admin
from django.contrib import messages
from rest_framework_api_key.models import APIKey
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'service', 'created', 'modified')
fieldsets = (
('Required Information', {'fields': ('name', 'service')}),
(... |
from setuptools import find_packages, setup
setup(
name='pbase',
version='0.0.1',
author='Peng Shi',
author_email='peng_shi@outlook.com',
description='framework for deep learning applications',
url='https://github.com/Impavidity/pbase',
license='MIT',
install_requires=[
],
pac... |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _c... |
"""Tests for capture2pcap."""
import os
import subprocess as sp
import sys
import capture2pcap
# Validate that the captured trace when run through capture2cap | tshark matches
# a golden output file for the tshark dump. Since we run capture2pcap in a
# subshell with a limited environment, the inferred time zone shou... |
__all__ = [
"NimiqClient",
"NimiqDict",
"InternalErrorException",
"RemoteErrorException",
"ConnectionErrorException",
"ConsensusState",
"AccountType",
"LogLevel",
"PeerAddressState",
"PeerConnectionState",
"PeerStateCommand",
"PoolConnectionState"
]
import requests
from ... |
# 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
from ... import _utilities, _tables
from... |
from anki.utils import stripHTMLMedia, intTime, ids2str
from aqt import mw
from aqt.qt import *
from aqt.utils import showInfo, chooseList, showText, getSaveFile, getFile
from itertools import chain
import json
import re
import sys
import time
MAX_RETRIES = 6
def exportDeck():
deckId = chooseDeck(prompt="Choose ... |
#!/usr/bin/env python
import smbus
class FieldMapper(object):
map = {}
def __init__(self, fields):
self.map = fields
def read(self):
assert False
def write(self, data):
assert False
def get(self, name):
bit = self.map[name]
data = self.read(... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
a=*map(int,input().split()),
r=1
for i in range(n):
x=y=a[i]
k=j=i
while j-1>=0 and a[j-1]<=x:j-=1;x=a[j]
while k<n and a[k]<=y:y=a[k];k+=1
r=max(r,k-j)
print(r)
|
# -*- coding: utf-8 -*-
# @Author: Kai Shen
# @Created Time: 2021/5/12 18:33
# @Organization: YQN
import torch
import torch.nn as nn
from backbone.multi_head_attention import MultiHeadAttention
from backbone.feed_forward import PoswiseFeedForWardNet
class DecoderLayer(nn.Module):
def __init__(self,n_heads,d_k,d_v,... |
from logging import getLogger
from typing import List, Optional, Tuple
from botocore.client import BaseClient
from botocore.exceptions import BotoCoreError, ClientError
from src.data.aws_organizations_types import Account, OrganizationalUnit
from src.aws_scanner_config import AwsScannerConfig as Config
class AwsOrg... |
from functools import reduce
listItems=[1,2,3,4,5,6,7,8,9,10]
print(listItems)
# without reduce
sum=0
for item in listItems:
sum=sum+item
print(sum)
# with reduce
sum1= reduce(lambda x,y:x+y,listItems)
print(sum1) |
opcao = int(input("Esolha uma opção"))
|
import sampler
import pandas as pd
from sklearn.metrics import accuracy_score,roc_auc_score
import datetime
def gete2t(train_size,truth_labels):
e2t = {}
for example in range(train_size):
e2t[example] = truth_labels[example]
return e2t
param = {
'annotation_file' : '../../../input/influencer_aij.... |
import numpy as np
def cam2pixel(cam_coord, f, c):
x = cam_coord[:, 0] / (cam_coord[:, 2] + 1e-8) * f[0] + c[0]
y = cam_coord[:, 1] / (cam_coord[:, 2] + 1e-8) * f[1] + c[1]
z = cam_coord[:, 2]
img_coord = np.concatenate((x[:, None], y[:, None], z[:, None]), 1)
return img_coord
def pixel2cam(pixe... |
import warnings
from logging import config, captureWarnings
from app.observability.flask import initialize_flask
def initialize_observability(conf, app=None):
# logging
config.dictConfig(conf['logging'])
captureWarnings(True)
warnings.simplefilter('ignore')
if app:
# flask
initia... |
#!/usr/bin/python
# Author:
# Marc Pucci (Vencore Labs)
# tmgr - traffic manager - controls a constellation of traffic nodes
# to gen and recv traffic from / to specific bound interfaces and ports
import sys
import json
import socket
import random
import string
import platform
import os
import subprocess
import tr... |
# -*- coding: utf-8 -*-
""" Time Periods.
Support for semesters/terms/etc.
Used mainly by Groups
"""
from ..lib.DB import run_sql, IntegrityError
from logging import log, ERROR
import datetime
import _strptime # import should prevent thread import blocking issues
# ask Google about: A... |
"""Gron's command line interface (CLI).
Attributes
----------
parser : argparse.ArgumentParser
"""
import argparse
import sys
from gron import gron
parser = argparse.ArgumentParser()
parser.add_argument(
'file',
help='A JSON file, if not given gron reads from STDIN',
nargs='?',
type=argparse.File... |
import asyncio
from functools import partial
from typing import List, Dict
from datetime import datetime, timedelta
async def thread_run(func, *args, **kwargs):
'''Run a blocking function in a thread.'''
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, partial(func, *args, **kwargs)... |
'''generate the vehicle position in carla world for this scenerio'''
import random
import numpy as np
import sys
from environments.carla_enviroments.carla_config import base_config
try:
sys.path.append(base_config.egg_file)
except IndexError:
pass
import carla
import time
from environments.carla_enviroments.c... |
from .root import root_logger |
# Imports, sorted alphabetically.
# Python packages
import sys
# Third-party packages
# Nothing for now...
# Modules from this project
from items import *
__all__ = (
'Inventory',
)
class Inventory(object):
sort_mode = 0
def __init__(self, slot_count = 27):
self.slot_count = slot_count
... |
from __future__ import absolute_import
def test_basics():
pass
# help.print_help("script", models.ArgList())
|
import collections
import collections.abc
import typing
from dataclasses import dataclass
from unittest.mock import patch
import pytest
from mashumaro import DataClassDictMixin, DataClassJSONMixin
from mashumaro.meta.helpers import (
get_class_that_defines_field,
get_class_that_defines_method,
get_generic... |
# _*_ coding: utf-8 _*_
# _Author_: 'Anson'
# _Time_: '2019-01-26 22:41' |
import pandas as pd
import numpy as np
import psycopg2
import sqlalchemy as db
import os
#func for list file on my folder dataset/
def list_file():
path = 'dataset/'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.csv' in file:
... |
#!/usr/bin/env python
from setuptools import setup
setup(
name='rdp',
version='0.1',
description='Recursive Decent Parser Library',
author='Johannes Dollinger',
author_email='emulbreh@googlemail.com',
url='http://github.com/emulbreh/rdp',
packages=['rdp'],
classifiers = [
"Prog... |
from decimal import Decimal
from django.conf import settings
from django.shortcuts import get_object_or_404
from products.models import Album
def cart_contents(request):
cart_items = []
total = 0
product_count = 0
cart = request.session.get("cart", {})
# Adds each item's id, quantity and album t... |
# Copyright 2016 The TensorFlow 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 applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.