content stringlengths 5 1.05M |
|---|
from datetime import datetime
from django.test import TestCase
from core.models import Raffle
class RaffleTestCase(TestCase):
def setUp(self):
self.name = 'raffle name'
self.description = 'raffle description'
self.contact = 'test@email.com'
self.draw_datetime = datetime.now()
... |
print("Hola Mundo")
print("Bienvenido, esta es una calculadora de sumas :), escribe tu nombre")
nombre=input()
print("Hola "+nombre+", introduce un número")
numA= float(input())
print("¿Cuanto le quieres sumar?")
numB= float(input())|
print("Calculadora de sumas")
total=numA+numB
print(nombre+", tu resultado es "+str(t... |
import datetime
from django.test import TestCase
from catalog.forms import RenewBookForm
class RenewBookFormTest(TestCase):
def test_renewal_date_field_label(self):
form = RenewBookForm(data = {
'renewal_date': datetime.date.today(),
})
self.assertEqual(
form.fie... |
"""This file contains all functions related to preprocessing."""
# pylint: disable=import-error
import os
import tqdm
import torch
import torchvision.transforms as transforms
# Data transformation
class DatasetTransformer(torch.utils.data.Dataset):
"""Apply transformation to a torch Dataset
"""
def __in... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: orc8r/protos/state.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from goo... |
a, b, c, d, e = map(int, input().split())
if a > b > c > d > e:
print("D")
elif a < b < c < d < e:
print("C")
else:
print("N") |
#!/usr/bin/env python
# coding=utf-8
'''
@Description:
@Author: Xuannan
@Date: 2019-11-26 09:05:26
@LastEditTime: 2020-03-30 22:29:36
@LastEditors: Xuannan
'''
from flask_restful import Resource,abort,reqparse
from app.apis.api_constant import *
from app.models import Crud,Lang,BlogContent,BlogContentTag, MaitulConten... |
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQPoints(self):
return self.qpoints
d... |
from sleekxmpp.test import *
class TestErrorStanzas(SleekTest):
def testSetup(self):
"""Test setting initial values in error stanza."""
msg = self.Message()
msg.enable('error')
self.check(msg, """
<message type="error">
<error type="cancel">
<fe... |
message_start = ("Oboeru - 'It's time to 覚える!")
message_instruction = ("Type 'start' to start quiz\n"
"Type 'quit' to quit '") |
from mountequist.impostors.http import Http
from mountequist.impostors.https import Https
|
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
""" Cons... |
# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2012 ITerativ GmbH. All rights reserved.
#
# Created on Jul 10, 2013
# @author: maersu <me@maersu.ch>
import os
from distutils.command.install import INSTALL_SCHEMES
from distutils.core import setup
packages = []
data_files = []
roo... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
base = os.path.dirname(os.path.abspath(__file__))
install_requires = [
'aiohttp==2.2.3',
'aiohttp_jinja2',
'asyncio',
'aiohttp_debugtoolbar==0.4.0',
'aiohttp_autoreload',
'schematics==2.0.0a1',
'aiopg==0.13.0',
... |
import os
import datetime
import setproctitle
from tf_rl.common.abs_path import ROOT_DIR as ROOT, ROOT_colab
from tf_rl.common.colab_utils import copy_dir
def set_up_for_training(env_name, seed, gpu_id, log_dir="Test", prev_log="", google_colab=False):
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
if prev... |
"""
MIT License
Copyright (c) 2020-2022 thatsOven
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... |
from secrets import choice
from string import ascii_uppercase, digits
ALPHABET = ascii_uppercase + digits
def generate_license_key(
parts: int = 4, chars_per_part: int = 8, separator: str = "-"
) -> str:
"""
Generate a license key of N parts.
For example with the default arguments you would get a st... |
# generic
from django.db.models import Q
from rest_framework import generics, mixins
from postings.models import ProjectPost
from .permissions import IsOwnerOrReadOnly
from .serializers import ProjectPostSerializer
class ProjectPostAPIView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field ... |
t = str(input())
n = len(t)
if n <= 140: print('TWEET')
else: print('MUTE')
|
# -*- coding: utf-8 -*-
# Copyright 2013 mysqlapi authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import signal
import crane_ec2
from mysqlapi.api import creator
from mysqlapi.api.models import DatabaseManager, Instance
o... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
results = []
... |
"""
Custom admin command to send fresh object_events via email.
The interval is provided in an argument.
Options:
realtime -> e.g. minute-by-minute
daily -> e.g. every day at midnight
weekly -> e.g. every sunday at 3 p.m.
monthly -> e.g. every last sunday of a month at 5 p.m.
The command always iterates... |
import pandas as pd
import threading
import time
from datetime import datetime
from utils import serve_websocket_data
# Usato per simulare fps perchè lanica lazione ogni "interval" secondi
class setInterval:
''' Run 'action' each 'interval' in async way.
Like javascript setInterval, see it to know behavior '... |
import numpy as np
import cv2
from renderer import plot_sdf
from curve import Curve
from util import ensure_dir, read_config
from transformer import transform
CURVE_PATH = '../curves/raw_data/'
CURVE_IMAGE_PATH = '../curves/raw_images/'
NORM_PATH = '../curves/normalized_data/'
NORM_IMAGE_PATH = '../curves/normalized_... |
import argparse
import sys
import time
from ledger import Amount
from tapp_config import setup_redis
from trade_manager import ses
from trade_manager.plugin import sync_ticker, get_ticker, sync_orders, make_ledger, get_orders, cancel_orders, \
get_balances, sync_balances, get_trades, sync_trades, create_order, sync... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 14 10:27:34 2021
@author: freeridingeo
"""
import sys
import numpy as np
sys.path.append("D:/Code/eotopia/IO")
from rasterio_IO import save_multibandraster_to_eopatch as saveit
import imageio
def create_rastertimeseries_gif(rasterpath, outpath,
... |
#!/usr/bin/env python
# An example of how to follow a trajectory defined using a set of waypoints for the first finger.
import rospy
from sr_robot_commander.sr_hand_commander import SrHandCommander
from sr_utilities.hand_finder import HandFinder
import geometry_msgs.msg
import copy
rospy.init_node("hand_example_foll... |
from django.core.mail import send_mail as django_send_mail
from keybar.tasks import celery
from keybar.utils.logging import logged
@logged
@celery.task(ignore_result=True, bind=True)
def send_mail_async(self, subject, message, from_email, recipient_list):
try:
django_send_mail(
subject, messa... |
import pytest
from matplotlib.figure import Figure
from pocs.utils.images import polar_alignment as pa_utils
@pytest.fixture
def pole_fits_file(data_dir):
return '{}/pole.fits'.format(data_dir)
@pytest.fixture
def rotate_fits_file(data_dir):
return '{}/rotation.fits'.format(data_dir)
def test_analyze_pol... |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Red Hat, 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
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... |
### Test
from dados import arquivo
from depth_first_search import dfs
from breadth_first_search.bfs import bfs
graph = arquivo.extract_data('grafo.txt')
if __name__ == '__main__':
path = dfs.dfs(graph, 'Salinas')
path_bfs = bfs(graph, 'Salinas')
print(graph)
print(path)
print(path_bfs) |
import tempfile
from itertools import chain
from os.path import join, exists
import random
from adapt.intent import Intent, IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler, \
intent_file_handler
from mycroft.messagebus import Message
from mycroft.skills.skill_data import read_vocab_file
f... |
from Compliant import types
import numpy as np
def createScene(node):
obj = node.createObject('MechanicalObject',
template = 'Rigid',
position = '0 0 0 0 0 0 1',
name = 'dofs')
# a rigid view on position vector
pos = np.... |
import pathlib
from typing import Dict, List, Optional, Union, cast
from urllib.parse import urlparse
import tldextract
import yaml
from email_validator import EmailNotValidError, validate_email
from pydantic import BaseModel, ValidationError
from pydantic.networks import AnyHttpUrl
class URLModel(BaseModel):
ur... |
from __future__ import unicode_literals
import os, json
from glob import glob
fileset = ("locale", "corpora")
def check(setname):
print "checking " + setname
mapping = dict((fName, set(json.load(open(fName)))) for fName in glob(setname + "*.json"))
def check_key(key, fromLang):
for fName, js... |
import sublime, sublime_plugin
import re
import random
import threading
from . import ShowImageInSublime
import re, os, shutil
from . import RandNetPicHelper
from . import RandNetPicGamerSky
from . import RandNetPicZbjuran
class RandomPicLoader():
def __init__(self):
self.loader = []
# self.loader.... |
# -*- coding: utf-8 -*-
__copyright__ = "Copyright (C) 2015 Mingxuan Lin"
__help__ = """
Dream3D Reader
==============
Transform the Dream3D RVE into DAMASK 'geometry' and 'material configuration' files.
"""
from ..ui import UIFilter
from .GeomFile import GeomFile
import numpy as np
from optparse import OptionParse... |
# Generated by Django 2.2.7 on 2019-11-23 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mujeres', '0002_mujer_paciente_enferma'),
('historiales', '0001_initial'),
]
operations = [
migrati... |
# coding: utf-8
"""
OpenAPI definition
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import... |
import os
import pyvisa
MOCK_FILE = os.path.join('marketplace', 'components', 'signal_generator',
'rs_smb100b', 'visa_sim.yml')
INST_ADDRESS = 'TCPIP0::1.2.3.4::INSTR'
class TestClass:
def setup_class(self):
""" setup_class called once for the class """
pass
def tear... |
def binary_string_to_binary_int(val):
return int(val, base=2)
def rotate_bits(bits, amount):
if amount >= len(bits): # more rotations than bits
amount = amount % len(bits)
# slice string in two parts for left and right
early = bits[0: len(bits) - amount]
late = bits[len(bits) - amount:]
... |
# Adding a Horizontal Legend to the Map
# https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
# https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
# https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.shp
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgi... |
#!/usr/bin/env python2
from __future__ import print_function
import sys
import os
import urllib
import argparse
import subprocess
import xml.etree.ElementTree as ET
import subprocess
VERBOSITY = 0
def warn(*msg):
for x in msg: print('[WARNING]', x, file=sys.stderr)
def error(*msg):
for x in msg: print('[ERROR]', x... |
# Copyright 2021 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... |
from ssc2ce.common.l2_book import L2Book
class CexL2Book(L2Book):
def __init__(self, instrument: str):
L2Book.__init__(self, instrument)
self.sequence = None
self.time = None
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from mininet.log import info
from mininet.util import pmonitor
from test_cases.test_case import TestCase
class DDOS(TestCase):
trigger = 'ddos'
packages = ['hping3']
def _exec_test(self, targets, int_hosts, ext_hosts, int_switches,
ext_switches... |
import getpass
import sys
import re
import math
import netrc
from datetime import datetime, timedelta
from optparse import OptionParser
from github import Github
from github.Repository import Repository
from github.GithubException import GithubException
repository = "html5rocks/www.html5rocks.com"
def ParseIssues(is... |
import TwitterClass
consumer_key = "" #GO TO TWITTER TO FIND THIS INFO
consumer_secret = ""
access_token = ""
access_token_secret = ""
twitterObj = TwitterClass.TwitterClass(consumer_key, consumer_secret, access_token, access_token_secret)
twitterObj.searchTweetsWithoutRT("#PyConES", 10)
|
version https://git-lfs.github.com/spec/v1
oid sha256:b97394d2c84f99dbd3d2d6f6a14f659367843433620914e7fd4d340cb4dc320a
size 11578
|
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = "d01"
__email__ = "jungflor@gmail.com"
__copyright__ = "Copyright (C) 2015-16, Florian JUNG"
__license__ = "MIT"
__version__ = "0.1.1... |
import numpy
n1=int(input())
#n2=int(input())
primeiro=n1/(numpy.log(n1))
segundo=1.25506*(n1/(numpy.log(n1)))
print('{:.1f} {:.1f}'.format(primeiro, segundo)) |
class Error(RuntimeError):
"""Superclass for all selecta-related exceptions."""
pass
class NotSupportedError(Error):
"""Exception thrown when something is not supported; for instance, the
combination of a terminal and a given UI class."""
pass
class TerminalInitError(Error):
"""Exception thr... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.reset_password_handler, name='password_resets'),
]
|
import _initpath
import os
import re
import collections
import pyradox
province_map = pyradox.worldmap.ProvinceMap(game = 'EU4')
colormap = {}
for filename, data in pyradox.txt.parse_dir(os.path.join(pyradox.get_game_directory('EU4'), 'history', 'provinces'), verbose=False):
m = re.match('\d+', filenam... |
SCREEN_HEIGHT = 650
SCREEN_WIDTH = 810
MIN_BOARD_HEIGHT = 6
MIN_BOARD_WIDTH = 6
START_SNAKE_SIZE = 3
BLOCK_SIZE = 30
HOW_MANY_BLOCKS_WIDTH = 20
HOW_MANY_BLOCKS_HEIGHT = 15
GAP_SIZE = 10
BACKGROUND_COLOR = (26, 26, 28)
BORDER_COLOR = (255, 191, 94)
SNAKE_COLOR = (121, 62, 16, 100)
PREY_COLOR = (72, 73, 84)
OPAQUE_ALP... |
from shiftevent.handlers import BaseHandler
class NoTypes(BaseHandler):
"""
This handler does not define EVENT_TYPES. It should always fail to
instantiate. Used for testing
"""
def handle(self, event): # pragma: no cover
""" Handle event """
pass
def rollback(self, event): ... |
import os
import sys
from code.classes.configuration import Configuration
from code.helpers.helpers import get_filenames, plot_networks
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: python trial_script.py input_data.txt")
_, input_data = sys.argv
directory = os.path.dirna... |
from leapp.actors import Actor
from leapp.models import StorageInfo
from leapp.reporting import Report
from leapp.libraries.common.reporting import report_with_remediation
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
class InhibitWhenLuks(Actor):
"""
Check if any encrypted partitions is in use. If ye... |
from launch import LaunchDescription
from launch_ros.actions import Node
import os
def generate_launch_description():
try:
hostname = os.environ["AIRSIM_HOSTNAME"]
except:
hostname = 'localhost'
return LaunchDescription([
Node(
package="tf2_ros",
node_executa... |
try:
from account.mixins import LoginRequiredMixin
except ImportError:
from django.contrib.auth.mixins import LoginRequiredMixin # noqa
|
# Copyright (c) 2018 Andy Zeng
# Library imports
import sys
import pickle
import numpy as np
from numba import njit, prange
from numba import cuda as ncuda
import torch
from skimage import measure
import skimage
try:
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
cuda.init()
pycuda_ctx = cu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20160322_2130'),
]
operations = [
migrations.AddField(
model_name='original',
name... |
from typing import Tuple
def interpolate(
value: float, value_range: Tuple[float, float], output_range: Tuple[float, float]
):
value_range_span = float(value_range[1] - value_range[0])
output_range_span = float(output_range[1] - output_range[0])
value_scaled = float(value - value_range[0]) / value_ran... |
#!/usr/bin/python
#
# web-reflect
#
# Copyright (c) 2020, Sanjeev Premi.
#
from argparse import ArgumentParser
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib import parse
import json
AllowCors = False
IsDebug = False
class ReflectServer(BaseHTTPRequestHandler):
__response = dict()
... |
import cv2
from tkinter import *
from PIL import Image,ImageTk
camera=cv2.VideoCapture(0)
master=Tk()
master.title('computer vision')
master.maxsize(width=640,height=480)
master.minsize(width=640,height=480)
tk_frame=Frame(master,width=640,height=480)
tk_frame.grid(row=0,column=0)
lb=Label(tk_frame)... |
'''
Checks if the
'''
import pexpect
import glob
import os
from rmodel import send_mail
from config import cn
import logging
import sh
import sys, math
try:
year = sys.argv[1]
except:
print "Usage:",sys.argv[0], "year or year_rm to remove data if the check is succesful"
sys.exit(1)
logging.basicConf... |
from django.core.management.base import BaseCommand
from logs.models import PendingAction
from scripts.models import Script
class Command(BaseCommand):
help = "Collection of tasks to run after updating the rmm, after migrations"
def handle(self, *args, **kwargs):
# remove task pending actions. depre... |
from django.shortcuts import render
# Create your views here.
import os
from rest_framework import viewsets, status, generics
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from rest_framework.decorators import api_view, permission_classes... |
import json
from urllib.parse import unquote_plus
import s3_helper
import os
import logging
from postgres_loader import PostgresLoader
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info('Loading function')
def lambda_handler(event, context):
DATABASE = os.getenv('DATABASE')
HOST = os.get... |
import FWCore.ParameterSet.Config as cms
# This is an ugly hack (but better what was before) to record if the
# loadDigiAliases() was called with premixing or not. Unfortunately
# which alias to use depends on that. If we had a premixing Modifier,
# this hack would not be needed.
_loadDigiAliasesWasCalledPremix = None... |
"""
Environments are JSON-serializable objects that fully describe how to run a flow. Serialization
schemas are contained in `prefect.serialization.environment.py`.
Different Environment objects correspond to different computation environments. Environments
that are written on top of a type of infrastructure also defi... |
#This program prints the number of asterisks entered.
#input
stars = int(input("How many stars do you want?"))
count = 0
#calculation
while (count < stars):
count += 1
#output
print()
print("*" * count)
#ask to quit
input("\nPress any key to quit...")
# Case 1
# How many stars do you want?20
# *******************... |
# Copyright 2018 AT&T Intellectual Property. All other 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 ... |
# Log configure
# The option are GENERAL, DETAILED, ALL
LEVEL = "DETAILED"
LOG_FILE = "running.log" |
import os
import subprocess
import log
PANDOC_PATH = '/usr/bin/pandoc'
def pandoc_convert(content):
""" pandoc text conversion """
informat = 'html'
outformat = 'plain'
converter = [PANDOC_PATH, '--from=%s' % informat, '--to=%s' % outformat]
#converter += ['--ascii', '-s', '--toc'] # some extra options
log.msg... |
# imports - compatibility imports
from bpyutils._compat import HTTPError
# imports - test imports
import pytest
# imports - standard imports
from bpyutils import request as req
def test_get():
res = req.get("https://httpbin.org/get")
assert res.ok
assert res.status_code == 200
json = res.json()... |
from .network_location import NetworkLocation
class Connection:
def send(self, data, *args, **kwargs):
"""
Used to send information to an external source,
send represents outgoing information, usually over-network but not exclusively
:param data: the data to be sent, a common use ... |
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from exif import Image as EXIFImage, WhiteBalance
from photometa.utils import safe_clear
from .models import Image
class TestExif(TestCase):
def setUp(self):
self.use... |
from screws.freeze.base import FrozenOnly
class _3dCSCG_ExactSolution_Allocator(FrozenOnly):
""""""
@classmethod
def ___exact_solution_name___(cls):
return {'icpsNS:TGV1' : 'TGV1',
'icpsNS:sincosRC': 'SinCosRebholz_Conservation',
'icpsNS:sincos_CCBF' : 'SinCos_... |
# -*- coding: utf-8 -*-
# License: See LICENSE file.
import math
import random
required_states = ['direction', 'position']
required_matrices = []
def run(name, world, matrices, states, target_y, target_x, wrap=False, get_closer=True, min_dist=1e-6, max_turn=math.pi/6):
d = states['direction'] % (2*math.pi)
y... |
#!/usr/bin/python
from sense_hat import SenseHat
sense = SenseHat()
sense.set_rotation(180)
red = (255, 0, 0)
sense.show_message("One small step for Pi!",scroll_speed=0.05, text_colour=[255,255,0], back_colour=[0,0,255])
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('request', '0005_alter_request_user'),
]
operations = [
migrations.AlterField(
model_name='request',
name='method',
field=models.CharField(default='GET', ... |
import os
import re
import pytest
import json
from contextlib import contextmanager
import jikken
from jikken.api import run_stage
from jikken.setups import MultiStageExperimentSetup
from jikken.multistage import STAGE_METADATA
def setup_database_stub(db):
@contextmanager
def db_stub():
yield db... |
'''
EXPLANATION:
Marks key:value pairs are
'alpha':[20,30,40]
'beta':[30,50,70]
query_name = 'beta'
the query_name is 'beta'. 'beta' average score is (30+50+70)/3 = 50.0
'''
CODE:
# Finding the percentage in Python - Hacker Rank Solution
if __name__ == '__main__':
n = int(input())
... |
"""Tests for parser module."""
import os
import responses
from histmag_to_kindle.parser import Parser
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
PAGE_1 = os.path.join(BASE_DIR, 'data/websites/page_1.html')
@responses.activate
def test_parser_parse_page(page_1):
"""Check if url is properly parsed in... |
#!/usr/bin/env python
"""A tool to learn Viterbi filter (Markov model) parameters from IGC files.
Learns parameters for the circling/not circling filter and for
the flying/not flying filter. Training data is loaded from
a directory.
"""
import os
import sys
from Bio.Alphabet import Alphabet
from Bio.HMM.MarkovModel i... |
import unittest
import bpy
from mathutils import (
Vector,
Color,
)
from blendergltf import utils
def extract_from_mesh(name):
mesh = bpy.data.meshes[name]
return utils.mesh.extract_attributes(mesh)
class TestMeshUtils(unittest.TestCase):
def test_extract_attributes_basic(self):
attrs =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto3
import click
import sys
import logging
import json
import os
# Setup logging using standard error.
logging.basicConfig(stream=sys.stderr,
level=logging.CRITICAL)
def create_session_resource(region, aws_type="ec2"):
resource = boto3.r... |
import numpy as np
from matplotlib import pyplot as pl
from matplotlib.colors import LogNorm
fn = '../pozo-steep-vegetated-pcl.npy'
pts = np.load(fn)
x, y, z = pts[:, 0], pts[:, 1], pts[:, 2]
ix = (0.2 * (x - x.min())).astype('int')
iy = (0.2 * (y - y.min())).astype('int')
shape = (100, 100)
xb = np.arange(x.min(), x... |
"""Seed command to read static torsion patterns"""
from django.core.management.base import BaseCommand
from torsion_analyzer.models import TorsionPattern
from torsion_analyzer.settings import MAPPING
class Command(BaseCommand):
"""Seed command to read static torsion patterns"""
help = 'Seeds database with sta... |
# Generated by Django 2.2.7 on 2019-11-21 19:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sitecampus', '0006_post_sutia'),
]
operations = [
migrations.AlterField(
model_name='autor',
name='semestre',
... |
# -*- coding: utf-8 -*-
"""Tests for common package."""
|
""" server.py """
from flask import Flask, request, jsonify, render_template
from pymongo import MongoClient
import json
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
app = Flask(__name__)
app.config.from_object(__name__)
app.config['MONGO_DBNAME'] = "mainAPP"
#connection = MongoClient('localhost', 27017)
connec... |
#!/usr/bin/env python
#
# Copyright (c) 2020 Open Infrastructure Foundation
#
# 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 requir... |
from implementations.knapsackProblem import knapsack_dynamic_solution
if __name__ == '__main__':
objects = {
'weight': [0, 5, 6, 2, 7, 1],
'value': [0, 4, 1, 5, 7, 8]
}
max_weight = 7
knapsack_dynamic_solution(objects, max_weight) |
#
# PySNMP MIB module HPN-ICF-NVGRE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-NVGRE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:40:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
count = 0
for i in range(13):
for j in range(11):
for k in range(9):
if 185 == i*15 + j*17 + k*21:
count += 1
print(i,j,k)
print("total ways -", count) |
import matplotlib.pyplot as plt
import os
import numpy as np
mediums = []
mediums1 = []
mediums2 = []
files = []
files1 = []
files2 = []
for filename in sorted(os.listdir('attack_defense_before0.02')):
if 'fgsm' in filename[1:5] and '2.5' in filename:
print(filename[-8:-4])
files.append(float(filena... |
from DLplatform.baseClass import baseClass
from DLplatform.parameters import Parameters
from typing import List
from multiprocessing import Process
from abc import ABCMeta
class Communicator(baseClass, Process):
'''
Abstract class for incapsulating all the methods for sending
and receiving messages in the... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <jun.zhu@xfel.eu>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
import os
import logging
from logging.handlers import TimedRo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.