content
stringlengths
5
1.05M
import math import pyglet import rabbyt from pyglet.gl import * from glart import * from sounds import * class MapDialogue: def __init__(self,window): self.window = window self.width = 500 self.height = 500 self.margin = [(window[0] - self.width) / 2 ,(window[1] - self.height) /...
#!/usr/bin/env python __description__ = 'SMTP honeypot' __author__ = 'Didier Stevens' __version__ = '0.0.2' __date__ = '2022/02/21' """ Source code put in public domain by Didier Stevens, no Copyright https://DidierStevens.com Use at your own risk History: 2018/03/24: start 2022/02/21: Python 3 fix Todo: """ i...
# pycn_lite/lib/flic_enc.py # (c) 2018-02-09 <christian.tschudin@unibas.ch> import pycn_lite.lib.packet import pycn_lite.client.cli # ---------------------------------------------------------------------- def bytesToManifest(repo, name, data): # input: byte array # output: (nameOfRootManifest, rootManifestC...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from tkinter import * from tkinter import messagebox from tkinter import scrolledtext import os class BoxingPage(): new_sn_list_submit = [] def __init__(self, master): self.master = master self.master.bind_all("<Control-r>", self.exit) se...
from django.shortcuts import render,get_object_or_404 from cart.cart import Cart from .models import OrderItem,Order from .forms import OrderCreateForm from .tasks import order_created from django.contrib.admin.views.decorators import staff_member_required import weasyprint from django.conf import settings from django....
import numpy as np import pandas as pd import matplotlib.pyplot as plt import pprint import config.settings import config.strategy from core.utility import chunk_trades, sharpe, drawdown from multiprocessing_on_dill import Pool #, Process, Manager from contextlib import closing class accountCurve(): """ Accou...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- import scrapy from scrapy_splash import SplashRequest from LosmliProxyPool.crawler.ajax.ajax.items import AjaxItem class CybersyndromeSpider(scrapy.Spider): name = 'cybersyndrome' allowed_domains = ['ybersyndrome.net'] start_urls = ['http://www.cybersyndrome.net/pld6.html'] ...
# -*- coding: utf-8 -*- # # S3XML Unit Tests # # To run this script use: # python web2py.py -S eden -M -R applications/eden/tests/unit_tests/modules/s3/s3xml.py # import unittest from gluon import * from gluon.contrib import simplejson as json # =========================================================================...
# coding: utf-8 import os import numpy as np import torch import torch.utils.data class MPIIGazeDataset(torch.utils.data.Dataset): def __init__(self, subject_id, dataset_dir): path = os.path.join(dataset_dir, '{}.npz'.format(subject_id)) with np.load(path) as fin: self.images = fin['...
#!/usr/bin/python3 import pandas as pd import numpy as np import matplotlib.pyplot as plt from util import * df = pd.read_csv('grants.tsv', sep='\t') areas = df.area.unique() years = df.year.sort_values().unique() group = df.groupby(['area', 'year']).amount.sum() print('{| class="sortable wikitable"') print("|-") p...
import json import pandas as pd //jsondata is a collection of data in json format //Used panndas dataframe to convert json data to dataframes table jdata = json.loads(jsondata) df = pd.DataFrame(jdata) //print(df.T)
# # Created by C. Cesarotti (ccesarotti@g.harvard.edu) 04/2019 # Last updated: 04/16/20 # # Contains code to calculate distance matrices for spherical, # ring like, and cylindrical geometries. # Also include code to calculate the EMD between two particle # physics collider events. # # Dependencies: POT library # ##...
from django.shortcuts import render import requests import pytz import datetime def trains(request): params = { "sort" : "-arrival_time", "filter[direction_id]" : "0", "page[offset]" : "0", "include" : "trip,schedule", "page[limit]" : "100", "filter[route_type]" : "...
import unittest from katas.kyu_6.is_prime import is_prime class IsPrimeTestCase(unittest.TestCase): def test_true(self): self.assertTrue(is_prime(2)) def test_false(self): self.assertFalse(is_prime(0)) def test_false_2(self): self.assertFalse(is_prime(1)) def test_false_3(s...
######################################## # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum GuestOsDescriptorFirmwareType = Enum( 'bios', 'efi', )
import click from eth_wallet.cli.new_wallet import ( new_wallet, ) from eth_wallet.cli.get_wallet import ( get_wallet, ) from eth_wallet.cli.reveal_seed import ( reveal_seed ) from eth_wallet.cli.get_balance import ( get_balance, ) from eth_wallet.cli.send_transaction import ( send_transaction, ) fr...
import os from typing import Any, Tuple import pandas as pd from config import CONFIG def loading_movielens_1m(file_path): ratings_header = "UserID::MovieID::Rating::Timestamp" movies_header = "MovieID::Title::Genres" user_header = "UserID::Gender::Age::Occupation::Zip-code" ratings = pd.read_csv( ...
#!/usr/bin/env python3 from argparse import ArgumentParser from datetime import date from os import getcwd from subprocess import run, check_call, CalledProcessError, Popen, PIPE from sys import exit import re r_log = re.compile('^.*app:(.*)$') APP_ENV_FILE = 'app.env' APP_SERVICE_NAME = 'app' def print_command(args...
# Modules on top of Pyro's poutine from __future__ import absolute_import, division, print_function import pyro from pyro.poutine.messenger import Messenger __all__ = ['simulator', 'simulate'] class simulator(Messenger): """ Inserts the effects of an online or offline simulator inside the executi...
# Copyright 2017 AT&T Corporation. # 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 require...
import netaddr from django.conf import settings from django.db.models import Count, Prefetch from django.db.models.expressions import RawSQL from django.shortcuts import get_object_or_404, redirect, render from django_tables2 import RequestConfig from dcim.models import Device, Interface from utilities.paginator impor...
# -*- coding: UTF-8 -*- from .base import * from .syntax import * from .syntactic import * from .semantic import * from .parser import * from .errors import * from .messages import *
from typing import Dict, List from fidesops.util.collection_util import append, merge_dicts, partition def test_merge_dicts() -> None: """Convert an iterable of dictionaries to a dictionary of iterables""" assert merge_dicts( [{"A": 1, "B": 2}, {"A": 2, "B": 3, "C": 4}, {"A": 4, "C": 5, "D": 6}] ...
""" Copyright (c) 2019-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ import unittest import warn...
#!/usr/bin/env python from distutils.core import setup setup(name='longshot', version='0.1alpha', description='SMOK client connectivity library', author='smok-serwis.pl', author_email='admin@smok.co', url='https://github.com/smok-serwis/longshot-python', packages=['longshot', 'long...
# Django settings for testproject project. import os.path import sys ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, os.path.abspath(os.path.join(ROOT_DIR, '..'))) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS =...
"""Example use of jupyter_kernel_test, with tests for IPython.""" import unittest import jupyter_kernel_test as jkt class BashKernelTests(jkt.KernelTests): kernel_name = "calysto_bash" language_name = "bash" code_hello_world = "echo 'hello, world'" completion_samples = [ { 'tex...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Nikita Seleznev, 2016 import math import matplotlib.pyplot as plt import numpy as np import sys from tkinter import Tk, Frame, Button, Scale, HORIZONTAL, Label, LEFT, CENTER, FLAT, GROOVE, filedialog from methods import explicit_euler, euler_with_recount, cauchy, \ ...
from time import sleep print("_-"*22) print(" Simulando um Banco") print("_-"*22) sleep(1) login = "Elivan" senha = "j" saldo = 1500 op = 99 while True: print("iniciando...") conflogin = str(input("\nDigite seu login: ")).strip() confsenha = str(input("Digite sua senha: ")).strip() print("\n...
#!/usr/bin/python from opencv.cv import * from opencv.highgui import * import sys # Rearrange the quadrants of Fourier image so that the origin is at # the image center # src & dst arrays of equal size & type def cvShiftDFT(src_arr, dst_arr ): size = cvGetSize(src_arr) dst_size = cvGetSize(dst_arr) if(ds...
#!/usr/bin/env python3 """ this will act as an extension to the g2j package and allow parsing of embl files. Idealy there the patterns in the original package are extended so only patterns have to be """ import re import tempfile import g2j from g2j import genbank PATTERNS = { "scaffold": re.compile(r"ID\s+?(...
from itertools import product import numpy as np import pandas as pd import torch from logic_crf.core import Factor def can_merge(fac1, fac2): if type(fac1) == type(fac2): can_merge_fn = fac1.fn.indexers[:-1] == fac2.fn.indexers[:-1] can_merge_mask = not ((fac1.mask != 0) & (fac2.mask != 0)).any...
import argparse import os import time import torch import torch.nn.functional as F import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transforms as transforms import flow_transforms import models import datasets from multiscaleloss import multisc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # dicts.py # USER_DATA_MASTER = {} TEXT_FIELD = 'Text Field' USER_DATA_MASTER["usertype"] = ["admin", "root", "std"] USER_DATA_MASTER["dateofreg"] = "" USER_DATA_MASTER["lastlogin"] = "" USER_DATA_MASTER["emailaddr_valid"] = ["false", "true"] def ge...
# # Licensed to Dagda under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Dagda licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance...
# -*- coding: utf-8 -*- """`TSIC2552 Standard <http://statstd.nso.go.th/classification/downloadcffile.aspx?id=73>`_. .. note:: Descriptions were translated using Google Translate. """ from ...types import Classification, Standard, Standards TSIC2552 = Standard( standard=Standards.TSIC2552, classes=[ ...
import numpy as np import pandas as pd from SALib.sample import saltelli import openturns as ot def get_saltelli_sample( problem: dict, n_saltelli: int, calc_second_order: bool = False ) -> pd.DataFrame: """Encapsulates Saltelli sampling function from SALib Parameters ---------- problem: dict ...
from pythonforandroid.toolchain import Recipe, shprint, current_directory from os.path import exists, join import sh class OpenSSLRecipe(Recipe): version = '1.0.2d' url = 'https://www.openssl.org/source/openssl-{version}.tar.gz' def should_build(self): return not exists(join(self.get_build_dir('...
#!/usr/bin/env python # This is a sample implementation of an editor. import os import pluginEditorDialogs import gtk from w3af import ROOT_PATH BLOCK_SIZE = 2048 RESPONSE_FORWARD = 1 class EditWindow(gtk.Window): def __init__(self, quit_cb=None): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) ...
from pydantic import BaseModel from typing import Optional class MachineLearningResponse(BaseModel): prediction: float class HealthResponse(BaseModel): status: bool
from data_science_layer.reporting.abstract_report import AbstractReport from data_science_layer.pipeline.abstract_pipline import AbstractPipeline from data_science_layer.scoring.mean_absolute_error_scorer import MeanAbsoluteErrorScorer import pandas as pd import pkg_resources from collections import defaultdict from da...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2018-12-21 16:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('search', '0010_auto_20181220_1614'), ] operations = [ migrations.AlterField...
import json import os from loguru import logger class JsonDict(dict): """ Stupid simple synchronous json-backed dict. Can be used as a contextmanager, in which case the dict will be json saved upon exiting context. Saves can be forced by calling `commit`. """ def __init__(self, *args, **kwar...
""" Module for creating all the spin boxes """ from PyQt5.QtWidgets import QSpinBox from constants import Hints, NORMAL_FONT from controller import handler from config import CONFIG def _set_config(spin_boxes): """ Set the states of the spin boxes based on the config """ base_configs = CONFIG["randomize"]["s...
# this is auto-generated by swagger-marshmallow-codegen from __future__ import annotations from swagger_marshmallow_codegen.schema.legacy import ( LegacySchema, PrimitiveValueSchema, ) from marshmallow import fields class IdsInput: class Get: pass class IdsIdInput: class Get: pass ...
import turtle alex = turtle.Turtle() alex.pensize(5) alex.penup() wn=turtle.Screen() wn.bgcolor("tan") alex.goto(-360, 120) alex.color("black") alex.pencolor("yellow") def Sand(): Sky() drawAllSun() Cactus() Camels() def square(): alex.forward(710) alex.left(90) alex.forward(...
""" Copyright (c) 2017-2020 ABBYY Production 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
import random import torch import torch.nn as nn import torch.nn.functional as F from .Attention import Attention class DecoderRNN(nn.Module): def __init__(self,vocab_size,max_len,dim_hidden,dim_word,n_layers=1,rnn_cell='gru',bidirectional=False,input_dropout_p=0.1, rnn_dropout_p=0.1): supe...
# encoding: utf-8 # ========================================================================= # ©2017-2018 北京国美云服科技有限公司 # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the ...
import json from typing import List import urllib.request from mysql_dbcon import Connection from model import GoogleChatWebhook def send_message_list(webhook_id: int, message_list: List[str]): with Connection() as cn: print('sending to chat...') webhook = cn.s.query(GoogleChatWebhook).filter(Goo...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import pytest import boto3 import json import requests import logging import re import os from requests_aws4auth import AWS4Auth # Fixture for retrieving env variables @pytest.fixture(scope='session') def te...
""" TODO """ import torch import torch.nn as nn import torch.nn.functional as F class ContentLoss(nn.Module): """ Measures how different the content is between two image. Important detail: although this module is named ContentLoss, it is not a true PyTorch Loss function. If you want to define your co...
#! /usr/bin/python3 from datetime import datetime from PIL import Image, ImageFilter, ImageDraw, ImageFont, ImageColor import json import math import subprocess import time color000000=ImageColor.getrgb("#000000") color8080FF=ImageColor.getrgb("#8080ff") colorC0C0C0=ImageColor.getrgb("#c0c0c0") colorC0C0FF=ImageColor....
import cv2 import argparse def main(): video_capture = cv2.VideoCapture(0) window_name = "video" while(True): _, frame = video_capture.read() cv2.imshow(window_name, frame) key = cv2.waitKey(1) # press ESC to close if key == 27: break ...
from ipctest import IpcTest class TestTicks(IpcTest): events = [] def on_tick(self, i3, e): self.events.append(e) if len(self.events) == 3: i3.main_quit() def test_tick_event(self, i3): i3.on('tick', self.on_tick) i3._event_socket_setup() i3.send_tick(...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("menu", "0002_menuitem_img")] operations = [ migrations.AddField( model_name="menuitem", name="enabled", field=models.BooleanField(default=True), preserve_...
# DAY 05 from collections import Counter def read_input(): ret = [] with open("./input.txt", "r", encoding="utf-8") as f: for line in f.readlines(): if line: print("* ", line) ret.append(parse_input_line(line)) return ret def parse_input_line(line_str): ...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
def even(n): return n % 2 == 0 def find_outlier(ints): find_odd = (even(ints[0]) and even(ints[1])) or (even(ints[1]) and even(ints[2])) or (even(ints[0]) and even(ints[2])) if find_odd: for i in ints: if not even(i): return i else: for i in ints: ...
import math import numpy as np import pandas as pd def check_availability(x1, x2): # print float(len(set(x1).intersection(set(x2)))) if float(len(set(x1).intersection(set(x2))))/len(x1) > 0: return True, float(len(set(x1).intersection(set(x2)))) return False, float(len(set(x1).intersection(set(x2)...
""" Python 3 Object-Oriented Programming Chapter 14. Concurrency """ import asyncio from pytest import * from unittest.mock import AsyncMock, Mock, call, sentinel import philosophers @fixture def mock_random(monkeypatch): random = Mock( random=Mock(side_effect=[0.2, 0.3]) ) monkeypatch.setattr(ph...
"""Fun Pligon For @PepeBot \nCode By © [Eyepatch](https://t.me/NeoMatrix90) \nType .nehi to see the fun. """ from telethon import events import asyncio import os import sys import random @borg.on(events.NewMessage(pattern=r"\.nehi", outgoing=True)) async def _(event): if event.fwd_from: return await ev...
''' Introduction ============ Carsus uses `sqlalchemy` to associate (experimental) data about real objects, such as atoms, with tables in a database. This allows us to store all data in one big database, but we can use it as if it were simple Python objects. Additionally, operations like filtering the data are perform...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import invertedindex_pb2 as invertedindex__pb2 class InvertedIndexStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A g...
import io from typing import Sequence, Any import pytest from revpbuf import parser @pytest.mark.parametrize( "test_input,expected", [ (b"\x00\x00\x20\x3e", (1042284544, 1042284544, 0.15625)), (b"\x00\x00\x20\xbe", (-1105199104, 3189768192, -0.15625)) ] ) def test_parser_fixed32_normal_input...
# Source: https://tinyurl.com/srucx8l """ The idea here is to build a segment tree. Each node stores the left and right endpoint of an interval and the sum of that interval. All of the leaves will store elements of the array and each internal node will store sum of leaves under it. Creating the tree t...
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-01 11:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('streams', '0001_initial'), ] operations = [ migrations.AlterField( ...
import sys from services.data_service import DataService from services.plot_drawing import PlotDrawingService def main(): args=sys.argv csv=args[1] x_column=int(args[2]) y_columns=list(map(lambda i: int(i), args[3:-1])) outname=args[-1] with open(csv, "r") as fs: ds=DataService(fs.read(...
from dataclasses import dataclass from typing import * @dataclass class TypeSchema: union_name: str classes: 'List[CaseTypeDef]' @dataclass class CaseTypeDef: typename: str fields: 'List[FieldDef]' @dataclass class FieldDef: name: Optional[str] type: 'Typ' @dataclass class Typ: basename:...
from enum import Enum from typing import List, Set from feed.errors import FeedVersionError FEED_NUM_DAYS = 1 DELIMITER = "+" class Format(str, Enum): PDF = "pdf" PS = "ps" @classmethod def supported(cls) -> List["Format"]: """Return a set of supported formats.""" return [cls.PS, ...
import os import sys import time import errno import signal import traceback import ave.config from ave.network.exceptions import * from ave.relay.server import RelayServer, RemoteRelayServer PID_PATH = '/var/tmp/ave-relay.pid' LOG_PATH = '/var/tmp/ave-relay.log' class RelayServerDaemon(RelayServer): def...
import tensorflow as tf i = tf.Variable(1) sum = tf.Variable(0) summing = sum.assign_add(i) increasing = i.assign_add(1) init = tf.global_variables_initializer() with tf.Session() as session: session.run(init) for i in range(5): summing.eval() increasing.eval() print(sum.eval())
# -*- encoding: utf-8 -*- import re from dataclasses import dataclass from typing import * import click import matplotlib.pyplot as plt import pandas as pd import requests @dataclass class MetricValue(object): __slots__ = ('mean', 'std') mean: Union[float, str] std: Optional[Union[float, str]] @datac...
import numpy as np import numpy.ma as ma from numpy import testing from numpy.testing import assert_array_equal import pytest import netCDF4 from cloudnetpy.products.iwc import IwcSource, IceClassification @pytest.fixture(scope='session') def categorize_file(tmpdir_factory, file_metadata): file_name = tmpdir_fact...
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="antfs", version="1.0.4", author="Anton Adamansky", author_email="adamansky@gmail.com", description="Python3 Apache Ant path patterns matching library", ...
# Copyright 2019 the wasserstein_fairness 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...
from changes.api.serializer import Crumbler, register from changes.api.serializer.models.user import get_gravatar_url from changes.models.author import Author @register(Author) class AuthorCrumbler(Crumbler): def crumble(self, instance, attrs): return { 'id': instance.id.hex, 'name...
import sys sys.path.append("D:\\Control\\PythonPackages\\") from serial import SerialException import threading import pbec_ipc from ThorlabsMDT69xA import ThorlabsMDT69xA class PiezoControllerServer(object): def __init__(self, glob=None): self.piezo_driver = None try: self.setEnabled(True) except Excepti...
#!/usr/bin/env python # # // SPDX-License-Identifier: BSD-3-CLAUSE # # (C) Copyright 2018, Xilinx, Inc. # import os, sys if len(sys.argv) <= 1: path = os.path.abspath(os.getcwd()) else: path = os.path.abspath(sys.argv[1]) origPath = path words2LookFor = ["MLsuite", "suite", "ML", "ml"] for word2LookFor in words2...
from flask import render_template from flask import request from website import app from flask import redirect, url_for # from sqlalchemy import create_engine # from sqlalchemy_utils import database_exists, create_database import pandas as pd # import psycopg2 import random import csv import sys sys.path.append('../'...
from apiclients.db import ResultsDbConnector import sys def delete(): exp_hash = sys.argv[1] table = sys.argv[2] print(f'About to delete experiment {exp_hash} from table {table}...') c = ResultsDbConnector('exploration') c.delete_row(exp_hash, table) print('Done') if __name__ == '__main__': ...
from rest_framework.permissions import BasePermission from wagtail_rest_pack.comments.models import Comment class CommentOwnerOrStaff(BasePermission): def has_object_permission(self, request, view, obj: Comment): user =request.user if user is None: return False created_by = ...
# Copyright 2015 47Lining 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
import torch import torch.nn.functional as F import torch.nn as nn import numpy as np from torch_geometric.nn import APPNP class MonoAPPNPModel(torch.nn.Module): def __init__(self, data, channels, dropout=0.8, K=10, alpha=0.10): super(MonoAPPNPModel, self).__init__() self.dropout = dropout ...
string = "bar" some_string = "%foo " <caret>+ string + " baz%"
from django.apps import apps from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.http import HttpResponse, StreamingHttpResponse, Http404, HttpResponseServerError from ..decorators import BaseDecorator from ..signals import dmp_signal_post_process_request, dmp_signal_pre_process_reque...
from turtlebot import Turtlebot, Rate # Names bumpers and events bumper_names = ['LEFT', 'CENTER', 'RIGHT'] state_names = ['RELEASED', 'PRESSED'] # Bumber callback def bumper_cb(msg): # msg.bumper stores the id of bumper 0:LEFT, 1:CENTER, 2:RIGHT bumper = bumper_names[msg.bumper] # msg.state stores the...
import random import unittest import numpy import os import isambard from unit_tests.random_isambard_objects import random_vectors, random_angles, random_floats,\ random_helical_helices, random_integer_vectors def check_dihedrals(polypeptide, phi=-65.0, omega=-178.0, psi=-41.0, atol=1): """ Returns True if ...
#!/usr/bin/env python from __init__ import __location__ import yaml import time import os def fmttime(timeobj): return time.strftime("%Y-%m-%dT%H_%M_%S", timeobj) start_time = time.gmtime() # Logger singleton # Must come before all other custom modules that use logging (e.g. auth). import logger log = logger....
"""Pnf resource module.""" """ Copyright 2021 Deutsche Telekom AG 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...
import pandas as pd import io import requests url="https://www.petrinex.gov.ab.ca/publicdata/API/Files/AB/Vol/2019-01/CSV" zipfile = ZipFile(io.BytesIO(requests.get(url).content)) filename = list(zipfile.NameToInfo.keys())[0] f = open(filename,'wb') f.write(zipfile.open(filename).read()) f.close() df=pd.read_csv(filen...
import json import logging import socket from django.conf import settings from django.contrib.sites.models import Site from django.http import HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect from django.shortcuts import render from django.utils.translation import ugettext as _ from django.views.decor...
'''Part 1 - Building the CNN''' '''Importing the Keras libraries and packages''' from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout '''Initialising the CNN''' classifier = Sequential() '''Step 1 - Convolution : Applying several feature detectors''' classifier....
from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from django.db.models import Q from .models import Discussion, DiscussionComment , DiscussionVote from .serializers import DiscussionSerializer , DiscussionC...
# -*- coding: utf-8 -*- from .blind_spot import BlindSpot from .knn import KNN from .outlier import Outlier from .perception import Perception from .range import Range
#!/usr/bin/env python # Copyright (C) 2016 Toyota Motor Corporation import controller_manager_msgs.srv import rospy import math import time import datetime import trajectory_msgs.msg import actionlib import control_msgs.msg import geometry_msgs.msg import os import sys import signal from sensor_msgs.msg import Image ...
import plotly from django.contrib.auth.models import User from django.views.generic import TemplateView from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework....
import json from nose.tools import assert_equals from .testapp import App, AuthApp TEST_EVENT = { "work_uri": "info:doi:10.11647/obp.0020", "measure_uri": "https://metrics.operas-eu.org/world-reader/users/v1", "timestamp": "2019-01-01T01:00:00", "country_uri": "urn:iso:std:3166:-2:ES", "value": 512...
#!/usr/bin/env python # # (c) Copyright Rosetta Commons Member Institutions. # (c) This file is part of the Rosetta software suite and is made available under license. # (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. # (c) For more information, see http://www.rosettacommons.or...