content
stringlengths
5
1.05M
# Make it possible to enable test coverage reporting for Python # code run in children processes. # http://coverage.readthedocs.io/en/latest/subprocess.html import os.path as op from distutils.sysconfig import get_python_lib FILE_CONTENT = """\ import coverage; coverage.process_startup() """ filename = op.join(get_p...
from django.db import models from django.utils.translation import gettext_lazy as _ from trade_system.users.models import User from trade_system.items.models import Item from trade_system.offers.choises import OrderType class Offer(models.Model): """Request to buy or sell specific stocks""" user = models.Fore...
from polylogyx.utils import js class Testjs: def test_pretty_operator(self): assert js.pretty_operator("equal") == "equals" def test_pretty_field(self): assert js.pretty_field("action")=="Action" def test_jinja2_esacpejs_filter_no_input(self): assert js.jinja2_escapejs_filter(Non...
from scipy.ndimage import convolve import numpy as np class Solution: def largestOverlap(self, A, B): B = np.pad(B, len(A), mode='constant', constant_values=(0, 0)) return np.amax(convolve(B, np.flip(np.flip(A,1),0), mode='constant'))
import pygame from pygame.sprite import Group from src import game_functions as gf from src.alien import Alien from src.button import Button from src.game_stats import GameStats from src.scoreboard import ScoreBoard from src.settings import Settings from src.ship import Ship def rungame(): # Initialize game,sett...
# -*- coding: utf-8 -*- """ @time : 2019/5/24 下午10:22 @author : [email protected] @file : cache_man.py @description : local_cache ########################################################## # # # # ########################################################## """ fr...
from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy import create_engine Base = declarative_base() class Knowledge(Base): __tablename__="knowledge" knowledge_id=Column(Integer, primary_k...
import logging import os import os.path import shlex import sys import re from io import StringIO from dimcli import CLI, logger cli = CLI() # taken from unittest/python 2.7 def assertDictSubset(actual, expected, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = ...
''' @author: aaditkamat @date: 27/12/2018 ''' def reverse_words(string): new_string = '' for word in string.split(' '): new_string += word[::-1] + ' ' return new_string print("Enter a string: ", end= '') string = input() print("Reverse of string \'", string, "\': ", reverse_words(string), sep='')
# -*- coding: utf-8 -*- import unittest from StringIO import StringIO from mock import patch from yalign.datatypes import Sentence from yalign.train_data_generation import * from yalign.train_data_generation import _aligned_samples, _misaligned_samples, _reorder, _random_range def swap_start_and_end(xs): xs[0],...
""" pyNRC - Python ETC and Simulator for JWST NIRCam ---------------------------------------------------------------------------- pyNRC is a set of Python-based tools for planning observations with JWST NIRCam, such as an ETC, a simple image slope simulator, and an enhanced data simulator. This package works for a va...
""" Tests that are reproductions of bugs found, to avoid regressions. """ from __future__ import print_function from unittest import TestCase, skipIf import numpy as np from numpy.testing import run_module_suite, assert_allclose from pkg_resources import parse_version import gulinalg class TestBugs(TestCase): de...
from django.utils.translation import ugettext_lazy as _ from django_filters import RangeFilter, Filter from mapentity.filters import MapEntityFilterSet class OptionalRangeFilter(RangeFilter): def __init__(self, *args, **kwargs): super(OptionalRangeFilter, self).__init__(*args, **kwargs) self.fiel...
# Generated by Django 2.2.3 on 2019-07-13 07:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rpsite', '0005_remove_evaluation_semaster'), ] operations = [ migrations.RemoveField( model_name='evaluationitem', name='que...
import warnings warnings.filterwarnings("ignore") import sys import time sys.path.append("../") from helper.utils import pd,random_seed_cpu_gpu,Print,read_pickle from config import * from tqdm import tqdm from os.path import join import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import...
import os import sys import time import mimetypes from http import HTTPStatus import logging from PIL import Image, ImageOps, ImageColor # from PIL import ImageFile # ImageFile.LOAD_TRUNCATED_IMAGES = True from twms import config from twms import correctify from twms import fetchers from twms import bbox as bbox_util...
# Consult the ruby example
# Copyright (c) 2016 Ericsson AB. # 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 ...
from .bloom_filter import BloomFilter from .counting_bloom_filter import CountingBloomFilter __all__ = ["BloomFilter", "CountingBloomFilter"]
import json from typing import Dict, Any, List, Optional from app.components.servers.game_server import GameServer from app.components.servers.server_config import ServerConfig class Config: def __init__(self, config_text: Optional[str]) -> None: if config_text is None: self.servers = [] ...
from rest_framework import serializers from .models import Profile,Post from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('name', 'bio','photo') class UserSerializer(serializers.ModelSerializer): class Meta:...
#!/usr/bin/env python3 import fileinput import math if __name__ == '__main__': factor = 1 / (2. * math.pi) for n in fileinput.input(): n = int(n) if n == 0: break print('%.2f' % (math.pow(n, 2)*factor))
from flask import render_template def city404(func): def wrapper(): try: return func() except KeyError: return render_template('error.html') return wrapper
#!/usr/bin/env python3 # # Copyright (c) 2020 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 from gdbstubs.arch.x86 import GdbStub_x86 from gdbstubs.arch.x86_64 import GdbStub_x86_64 from gdbstubs.arch.arm_cortex_m import GdbStub_ARM_CortexM from gdbstubs.arch.risc_v import GdbStub_RISC_V from gdbstubs.arch...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/data/pokemon_display.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf imp...
import csv #------------------------------------------------------------------------------- def dSdt(beta, gamma, N, t_n, s_n, i_n): return (-beta*i_n*s_n)/N def dIdt(beta, gamma, N, t_n, s_n, i_n): return ((beta*i_n*s_n)/N)-gamma*i_n def dRdt(beta, gamma, N, t_n, s_n, i_n): return gamma*i_n #--------...
from unittest import TestCase from unittest import main from integer_difference import int_diff class TestIntegerDifference(TestCase): def test_int_diff(self): ptr = [ ([1, 1, 5, 6, 9, 16, 27], 4, 3), ([1, 1, 3, 3], 2, 4), ] for inp, d, exp in ptr: with...
import torch # TODO: write docstrings class SimpleDynamics(torch.nn.Module): def __init__(self, dynamics_function, divergence_estimator): super().__init__() self._dynamics_function = dynamics_function self._divergence_estimator = divergence_estimator def forward(self, *x...
from DealUUIDGenerator import DealUUIDGenerator class TestClass(object): def test_singleExchangeConstantProfit(self): dealUUIDGenerator = DealUUIDGenerator() id1 = dealUUIDGenerator.getUUID(timestamp=1, volBTC=1, nodesStr="bitstamp,coinbasepro", profitPerc=0.5) id2 = dealUUIDGenerator.get...
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes import gc class RSA_key_gen(): ...
from . import deploy
import time root = 'own/' buffer = 'buffer.txt' memory = 'memory.txt' # python own/test.py | ./pokemon-showdown simulate-battle > own/buffer.txt def empty_files(): fmemory = open(root + buffer, mode='w') fmemory.close() fbuffer = open(root + memory, mode='w') fbuffer.close() def read_last_showdown_message()...
# -*- coding: utf-8 -*- """Forms to process attributes and sharing.""" from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from ontask import is_legal_name from ontask.models import Condition CHAR_FIELD_SIZE = 1024 class AttributeItemForm...
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.utils.decorators import method_decorator from django.contrib.auth.decorators im...
#!/usr/bin/env python # -*- coding: utf-8 -*- #__author__ = 'ifk' #Refer http://www.wooyun.org/bugs/wooyun-2010-043380 import urlparse def assign(service, arg): if service == "fsmcms": return True, arg def audit(arg): payload = '/setup/index.jsp' code, head, res, errcode, _ = cu...
#!/usr/bin/env python """ nxosm was written to extract and build a road network using OSM data; to build adjacency matrix with geolocation information for each node. Citation Format: Legara, E.F. (2014) nxosm source code (Version 2.0) [source code]. http://www.erikalegara.net """ __author__ = "Erika Fille L...
# Generated by Django 2.1.9 on 2019-07-23 08:14 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [("terra_layer", "0032_auto_20190718_1742")] operations = [ migrations.AddField( model_name="layergroup", ...
# https://leetcode.com/problems/pascals-triangle-ii/ # Related Topics: Array # Difficulty: Easy # Initial thoughts: # The naive solution is to handle this problem like with did Pascal's Triangle where we create a two dimensional array # with the values of Pascal's triangle up to the row that we need to return and ...
import unittest import euler class TestGCD(unittest.TestCase): def test_gcd(self): self.assertEqual(euler.gcd(3, 5), 1) self.assertEqual(euler.gcd(5, 13), 1) self.assertEqual(euler.gcd(2, 10), 2) self.assertEqual(euler.gcd(5, 10), 5) self.assertEqual(euler.gcd(10, 25), 5)
########################################################################### # # Copyright 2018 Google 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 # # https://www.apache.org/...
import typing from ParadoxTrading.Fetch.ChineseFutures.FetchBase import FetchBase from ParadoxTrading.Utils import DataStruct class FetchInstrumentTickData(FetchBase): def __init__( self, _mongo_host='localhost', _psql_host='localhost', _psql_user='', _psql_password='', _cache_path='cache...
""" Syntax ^^^^^^ lambda arguments : expression """ fx = lambda: print("This is lambda") fx() fx = lambda arg: print(f'This is {arg}') fx("lambda") # Variable Arguments (Positional) fx = lambda *arg: print(f'This is {arg[0]}') fx("lambda1", "lambda2") # Variable Arguments (Key Value pairs) fx = lambda **arg: prin...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import hmac import requests from time import time from hashlib import sha256 from .exceptions import AuthorizedError class _TuyaApi: """ Private class for API requests """ def __init__(self, client_id: str, secret_key: str, region_key: str)...
from django.urls import path from . import views from django.contrib.auth import views as auth_views from django.conf.urls import url app_name = 'accounts' urlpatterns = [ path('signup/', views.signup_view, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view,...
start = [8,13,1,0,18,9] last_said = None history = {} def say(num, turn_no): print(f'turn {i}\tsay {num}') for i in range(30000000): if i < len(start): num = start[i] else: # print(f'turn {i} last said {last_said} {history}') if last_said in history: # print('in') ...
import torch from torch import Tensor from tree_expectations import N from tree_expectations.utils import device def laplacian(A: 'Tensor[N, N]', rho: 'Tensor[N]') -> 'Tensor[N, N]': """ Compute the root-weighted Laplacian. Function has a runtime of O(N^2). """ L = -A + torch.diag_embed(A.sum(dim...
# Generated by Django 3.1.5 on 2021-04-21 07:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('posts', '0001_initial'), ('groups', '0001_initial'), ('profiles', '0001_initial'), ]...
import torch import torch.nn as nn from block import FC_block sp = torch.zeros((1, 1)) counter = 0 class SNN(nn.Module): def __init__(self, hyperparams, hidden_size, layers=3, sbp=False, bp_mark=None): super(SNN, self).__init__() self.hyperparams = hyperparams self.hidden_size = hidden_siz...
# Copyright 2017 Google 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 # # Unless required by applicable law or a...
""" ********************************************************* * * * Project Name: Recursive Fibonacci Sequence * * Author: github.com/kirigaine * * Description: A simple program to put in how many * * numbers of the Fibonac...
# Copyright 2020 Skillfactory LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
import lionchief import time import logging import sys logging.basicConfig() logging.getLogger('bluetooth').setLevel(logging.DEBUG) # Replace this mac address with the one # belonging to your train #chief = lionchief.LionChief("44:A6:E5:48:7F:73") #steam engine chief = lionchief.LionChief("44:A6:E5:35:54:88") #GE # s...
""" set and catch alarm timeout signals in Python; time.sleep doesn't play well with alarm (or signal in general in my Linux PC), so we call signal.pause here to do nothing until a signal is received; """ import sys, signal, time def now(): return time.asctime() def onSignal(signum, stackframe): ...
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
from sklearn.metrics import silhouette_samples, silhouette_score import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import ticker from matplotlib.colors import to_hex import numpy as np import pandas as pd import os import argparse from .utils import str2bool,setColorConf USAGE=""" Desc: script ...
from keras.models import Sequential from keras.layers import Dense, LSTM import keras.backend as K import numpy as np import tensorflow as tf a = [1, 0, 0] b = [0, 1, 0] c = [0, 0, 1] seq = [a, b, c, b, a] x = seq[:-1] y = seq[1:] window_size = 1 x = np.array(x).reshape((len(x), window_size, 3)) y = np.array(y) nu...
from Hw.H8_Seq2Seq.config import configurations from Hw.H8_Seq2Seq.train import train_process import torch import os device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 判斷是用 CPU 還是 GPU 執行運算 config = configurations() if not os.path.isdir(config.store_model_path): os.mkdir(config.store_model_pat...
# (c) Copyright IBM Corp. 2019. All Rights Reserved. # -*- coding: utf-8 -*- """Generate the Resilient customizations required for fn_service_now""" from __future__ import print_function from resilient_circuits.util import * def codegen_reload_data(): """Parameters to codegen used to generate the fn_service_now ...
# Copyright 2021 STC-Innovation LTD (Author: Anton Mitrofanov) import sys import logging import os def setup_logger(exp_dir=None, log_fn="training.log", stream=sys.stdout, logger_level=logging.INFO, logfile_mode="w"): logger = logging.getLogger() logger.setLevel(logger_level) logger.handlers.clear() ...
[262144, 18, 0, 0, 0, 0.43696], [262440, 3, 8, 1, 0, 0.626528], [262500, 2, 1, 5, 1, 0.828288], [263424, 8, 1, 0, 3, 0.762944], [264600, 3, 3, 2, 2, 0.691968], [268800, 9, 1, 2, 1, 0.71488], [268912, 4, 0, 0, 5, 0.754944], [270000, 4, 3, 4, 0, 0.609312], [272160, 5, 5, 1, 1, 0.72368], [273375, 0, 7, 3, 0, 0.7416], [274...
""" This module is intended to allow deploying of arbitrary Azure Resource Manager (ARM) templates and describe the provided DC/OS cluster. For more information on how to configure and interpret these templates, see: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authoring-templates """ i...
import logging import requests from ...models import Configuration # pylint: disable=too-few-public-methods class PushNotificationSender: logger = logging.getLogger(__name__) fcm_url = "https://fcm.googleapis.com/fcm/send" """ Sends push notifications via FCM legacy http api. Returns boolean ind...
# Copyright (c) 2011, Found IT A/S and Piped Project Contributors. # See LICENSE for details. import socket import mock from twisted.trial import unittest from twisted.internet import defer, reactor from twisted.application import service from twisted.python import reflect, log from twisted.spread import pb, flavors f...
import logging import os from distutils.util import strtobool from typing import Any, Callable, MutableMapping, Optional from aiohttp.web import Application, run_app, static from aiohttp_jinja2 import setup as setup_aiohttp_jinja2 from aioredis import create_redis_pool from jinja2 import FileSystemLoader from .cac...
#!/usr/bin/env python3 import configparser import requests import argparse import json import re import yaml import os import subprocess import shutil from glob import glob # Get config from user dir config_file = os.path.expanduser("~/.puzzlecad") config = configparser.ConfigParser() config.read(config_file) client...
import pytest import dataset import pymemdb @pytest.fixture(scope="function") def simple_dataset_db(): db = dataset.connect("sqlite:///:memory:", row_type=dict) simple_table = db.create_table("my_table") simple_table.insert_many([dict(a=i, b=1) for i in range(10)]) return db def test_simple_table(...
"""Tools for defining and modeling problem geometry This module implements several kinds of collision detection, as well as tools for converting between different representations of problem geometry. The supported geometry types are referred to as :math:`\\mathbf{R}^2` (where the robot is a point navigating in a polyg...
# Copyright 2021 The Pigweed 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
from event_testing.resolver import DoubleSimResolver from event_testing.results import TestResult from event_testing.test_events import cached_test from interactions import ParticipantTypeSingle from interactions.constraint_variants import TunableGeometricConstraintVariant from interactions.constraints import Anywhere ...
from dataclasses import dataclass from records import RecordBase from tests.benchmarking.util import Benchmark bm = Benchmark('construction') class REC_Point(RecordBase): x: float y: float z: int = 0 w: str = "" @bm.measure(source=(REC_Point, ...), highlight=True) def new_record(): REC_Point(x...
from website.addons.dropbox import model, routes, views MODELS = [model.DropboxUserSettings, model.DropboxNodeSettings, model.DropboxFile] USER_SETTINGS_MODEL = model.DropboxUserSettings NODE_SETTINGS_MODEL = model.DropboxNodeSettings ROUTES = [routes.auth_routes, routes.api_routes] SHORT_NAME = 'dropbox' FULL_NAME...
print ("hello world") print ("123") x =12 print (x)
#!/usr/bin/env python """Wrapper around curl to add HMAC signatures.""" import os import subprocess import sys from lcp_mac import generate_authorization_header_value def get_http_method(argv): if '-X' not in argv: return 'GET' i = argv.index('-X') return argv[i+1] def get_url(argv): for ar...
# TimeConver.pt # Using the Python language, have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon. def TimeConvert(num): int...
import matplotlib.pyplot as plt import numpy as np def kernel(x, t): return np.exp(-x**2/(4*t)) xx = np.linspace(0, 2, 100) t = 0.5 plt.plot(xx, kernel(xx, t)) for x in np.linspace(0, 2, 11): if x: """if x<0.3: plt.plot([x, x], [0, kernel(x, t)], 'r--')""" plt.plot([x, x], [0, k...
""" Funções - def em Python (Parte 2) """ def divisao(n1, n2): if n2 > 0: resultado = n1 / n2 return resultado divide = divisao(8, 1) if divide: print(divide) else: print('Conta não válida') def funcao(var): print(var) variavel = funcao variavel('Teste')
JSON_API_HEADERS = { 'Content-Type': 'application/vnd.api+json', 'Accept': 'application/vnd.api+json' }
# Copyright 2017 Cloudbase Solutions Srl # 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 r...
"""General utilities""" import json import datetime import os import re import sys from .exceptions import CloudPassageValidation from .exceptions import CloudPassageAuthentication from .exceptions import CloudPassageAuthorization from .exceptions import CloudPassageResourceExistence from .exceptions import CloudPassag...
import tensorflow as tf import numpy as np from PIL import Image from tensorflow.keras import layers import os import matplotlib.pyplot as plt from tensorflow.keras.applications import VGG16,MobileNet from tensorflow.keras.applications import imagenet_utils from tensorflow.keras.preprocessing.image import loa...
import functools from app.master.cluster_master import ClusterMaster from app.subcommands.service_subcommand import ServiceSubcommand from app.util import analytics, log from app.util.conf.configuration import Configuration from app.web_framework.cluster_master_application import ClusterMasterApplication class Maste...
# 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, software # d...
""" 2021/02/20 writen by Runze Dong Multiple Eavesdroppers Scenario """ from fun_multiEve import * from tensorflow.python.keras.layers import * # import os # os.environ['CUDA_VISIBLE_DEVICES'] = '2,3' P_a = np.expand_dims(10**(np.linspace(-10, 10, 11)/10)/(beta_0*d_b**(-1*eta_b))*delta_[1, :], 0) R_s1 = np.zeros([1, P...
from __future__ import absolute_import, division, print_function import os, sys import numbers import random import numpy as np import copy from PIL import Image import PIL.Image as pil import fire from collections import defaultdict import torch import torch.nn.functional as F from torch.utils.data import Dataset f...
#Retrieving coin information from coingecko, creating a coin_names ls # See https://www.coingecko.com/en/api from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() coin_list = cg.get_coins_list() coin_names = {} for coin in coin_list: name = coin['name'] coin_id = coin['id'] coin_names[name] ...
from collections import deque class Agent(object): def __init__(self, plan=[], current_travel_time=0, time_to_pass_link=0, identifier="unset"): self.__setstate__({ "plan": deque(plan), "current_travel_time": current_travel_time, "time_to_pass_link": time_to_pass_link, "id": str(identifier) })...
welcome = input("Welcome to Prince's Basic calculator of Addition, Please Click Enter to continue !") print(welcome) num_1 = float(input("Enter Your First Number : ")) num_2 = float(input("Enter yoir Second Number : ")) result = round(num_1 + num_2, 2) print(f"Your result is : {num_1+num_2}") thank = input(...
import os import re import csv import sys import json import time import errno import random import urllib import logging import datetime import requests from bs4 import BeautifulSoup from selenium import webdriver #driver = webdriver.Chrome('./cdriver/chromedriver.exe') # #driver.get("https://www.wg-gesucht.de/en/")...
from __future__ import absolute_import import logging import six import threading from collections import defaultdict from sentry.debug.utils.patch_context import PatchContext DEFAULT_MAX_QUERIES = 25 DEFAULT_MAX_DUPES = 3 class State(threading.local): def __init__(self): self.count = 0 self.q...
import magma as m from mantle.xilinx.spartan6.SRL import SRL16 from loam.boards.papiliopro import PapilioPro from loam.shields.megawing import MegaWing megawing = MegaWing(PapilioPro) megawing.Clock.on() megawing.Switch.on(5) megawing.LED.on(1) main = megawing.main() A = main.SWITCH[0:4] I = main.SWITCH[4] O = main.L...
def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key lst = [1, 2, 3, 5, 4] insertionSort(lst) # since lists are mutable # the main list itself changes print(l...
from django import forms from .models import Customer class CustomerForm(forms.ModelForm): """ Форма покупателя для интерфейса кладовщика. """ class Meta: model = Customer fields = '__all__' widgets = {'contact_info': forms.Textarea(attrs={'rows': '2', ...
""" A module simulating a device using multiple threads to collect and parse data imitating a crowdsense environment. """ from threading import Thread import constants from synchronize import Synchronize from task import Task from thread_pool import ThreadPool class Device(object): """ Class that represents...
import os import shutil import time from typing import Iterator import pytest from py._path.local import LocalPath @pytest.fixture def here() -> str: """Returns the absoluate path of the project root Returns: str: path """ return os.path.abspath(os.path.dirname(__file__)) @pytest.fixture de...
import pygame from agent import Agent class MyAgent(Agent): def get_action(self, state, last_action, time_left): played = False action = None while not played: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() valid_clic = False if state...
from eliot import log_call from .extract_user_from_req import extract_user_from_req @log_call def extract_uid_from_req(req, hdr_name, claim_field): return extract_user_from_req(req, hdr_name, claim_field)["uid"]
""" @file qliblabels.py @author xy @since 2014-08-09 @brief qLib, node tagging/labeling functions (semantics). """ import hou import re import traceback import datetime import sys labels = { # a completed partial-result 'waypoint': { 'cats': ('so...
""" Synchronize Azure network security rules """ from common.methods import set_progress from azure.common.credentials import ServicePrincipalCredentials from resourcehandlers.azure_arm.models import AzureARMHandler from azure.mgmt.network import NetworkManagementClient from msrestazure.azure_exceptions import CloudErr...
import argparse import json import requests import properties def retrieve_data(pubmedIds): base_url = properties.base_url efoTraits = properties.efoTraits search = properties.uriSearch # Header print("EFO trait, URI") print(" Author, publication date, title, journal, pubmed Id, accession I...
""" Goal: compute the shortest path given source node s and target node t. Preprocessing phase: Query Phase: Similar to dijkstra, but we only follow edges going to nodes with a higher contraction order than the current node """ class ContractionHierarchy(object): def __init__(self): pass def preproce...