content
stringlengths
5
1.05M
from Player import * class GA: population = [] bestp = [] victory = False bestPlayer = None def __init__(self, gen, popsize, mr, init, end, maze): self.gen = gen self.curgen = 0 self.popsize = popsize self.mr = mr self.init = init self.end = end ...
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import memcache from webnotes import conf class MClient(memcache.Client): """memcache client that will automatically prefix conf.db_name""" def n(self, key): return (conf...
#!/usr/bin/env python # Copyright 2020-2021 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # 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...
import numpy as np def top_k_accuracy(probs, labels, k=5): """Calculate the Top-k Accuarcy. Args: probs (np.array): [batch_size, num_class] matrix. labels (np.array): [batch_size] matrix. Returns: accuracy (float): top k accuracy. """ correct = 0 for i in range(probs.shape[0]): p_ = pr...
#!/usr/bin/python """ RaceScore """ import io from setuptools import setup with io.open('requirements-testing.txt') as fd: test_reqs = fd.readlines() tests_require = [line for line in test_reqs if not line.startswith('#')] with io.open('README.rst') as fd: long_desc = fd.read() setup( name = 'race-sc...
import json import time import numpy as np import os import sys from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtCore import pyqtSignal from twisted.internet.defer import inlineCallbacks sys.path.append('./forms/') from input_forms import InputForms from output_forms import OutputForms from gui_defaults...
from pprint import pprint import warnings import pygame as pg try: from _internal import COLOURS except ImportError: from ._internal import COLOURS LARGEICONSIZE = 10 warnings.warn("This Inventory module is DEPRECATED. please use the better one", DeprecationWarning) class InventoryHandler: def __init_...
import unittest from torch.utils.data.dataloader import DataLoader from avalanche.benchmarks import Experience, SplitCIFAR100, SplitCIFAR110 from tests.unit_tests_utils import load_experience_train_eval CIFAR10_DOWNLOADS = 0 CIFAR10_DOWNLOAD_METHOD = None CIFAR100_DOWNLOADS = 0 CIFAR100_DOWNLOAD_METHOD = None clas...
""" Property of UAS C2C2 Senior Design Team 2019 Team Members: Mark Hermreck, Joseph Lisac, Khaled Alshammari, Khaled Alharbi Questions about this code can be directed toward Mark Hermreck at markhermreck@gmail.com """ from dronekit import connect, LocationGlobal, LocationGlobalRelative, Vehicle, VehicleMode, Co...
from itertools import count from typing import Optional, Tuple, Union import numpy as np from matplotlib import patches from ..lattice import Lattice from .base import BaseElement from .utils import straight_element class Quadrupole(BaseElement): """Quadrupole element. Args: k: Strength in meters^-...
# -*- coding: utf-8 -*- __author__ = "苦叶子" """ 公众号: 开源优测 Email: lymking@foxmail.com """ from datetime import datetime from flask import url_for from flask_restful import Resource, reqparse from flask_login import current_user from sqlalchemy import and_ from ..models import AutoProduct, AutoProject, AutoSuite, A...
from decorators import do_twice @do_twice def say_whee(): print("Whee!") say_whee()
# -*- coding: utf-8 -*- import os import json from tqdm import tqdm import numpy as np from pydicom.filereader import dcmread import pylidc as pl from pylidc.utils import consensus from pylidc.Annotation import feature_names OUTPUT_PATH = '/localdata/LIDC-IDRI_labels' os.makedirs(OUTPUT_PATH, exist_ok=True) DATA_PATH...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pygame raycaster # import math import pygame from pygame.locals import * m = [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,1,0,...
class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ for row in matrix: for col in xrange(1, len(row)): row[col] += row[col-1] self.matrix = matrix def...
from typing import Optional, Tuple, Callable, Union, List import logging import numpy as np import torch from gpytorch import ExactMarginalLogLikelihood from gpytorch.constraints import GreaterThan from gpytorch.likelihoods import GaussianLikelihood from torch import Tensor from torch.distributions import Normal from ...
import termscreen from colorama import init, deinit # Fore, Back, Style import time import datetime import math import prime_numbers init() termscreen.cls() print('{:*^80}'.format(' \x1b[33;1mПроект Эйлера\x1b[0m ')) print('{:^80}'.format('\x1b[32mhttp://projecteuler.net/archives\x1b[0m')) # Task 003 print(''' За...
from osm_observer.extensions import db from geoalchemy2.types import Geometry from sqlalchemy.dialects.postgresql import HSTORE __all__ = [ 'changesets', 'nodes', 'ways', 'relations', 'comments', 'nds', 'members', 'current_status' ] changesets = db.Table( 'changesets', db.MetaData(), db.Column('id', d...
# MQTT Logger for MicroPython by Thorsten von Eicken (c) 2020 # # Requires mqtt_async for asyncio-based MQTT. #!!!!!!!!!! This code was pulled out of mqrepl and is not finished. It's probably better to #!!!!!!!!!! hook Logging and make sure all errors and exceptions result in calls to Logging. #!!!!!!!!!! This way ver...
# # 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...
import six from .helper import TypeFactory from collections import defaultdict from .errors import ValidationError # Validators class Validator(object): """Callable base class to validate a given value""" def __call__(self, value): self.validate(value) class StringValidator(Validator): """Valid...
import copy import os from gxformat2.converter import python_to_workflow, STEP_TYPES, yaml_to_workflow from gxformat2.export import from_galaxy_native from gxformat2.interface import ImporterGalaxyInterface TEST_PATH = os.path.abspath(os.path.dirname(__file__)) TEST_INTEROP_EXAMPLES = os.environ.get("GXFORMAT2_INTERO...
from scipy import ndimage as ndi import numpy as np import scipy from bokeh.io import curdoc from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource from bokeh.models.widgets import Slider, TextInput from bokeh.layouts import row, widgetbox from bokeh.layouts import gridplot from bokeh.client ...
from py_crypto_hd_wallet.monero.hd_wallet_monero_enum import ( HdWalletMoneroWordsNum, HdWalletMoneroLanguages, HdWalletMoneroCoins, HdWalletMoneroDataTypes, HdWalletMoneroKeyTypes ) from py_crypto_hd_wallet.monero.hd_wallet_monero_factory import HdWalletMoneroFactory from py_crypto_hd_wallet.monero.hd_wallet_m...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayMarketingCampaignPrizeAmountQueryResponse(AlipayResponse): def __init__(self): super(AlipayMarketingCampaignPrizeAmountQueryResponse, self).__init__() ...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import sys, timeit from typing import List def part01(input: List[int]): result = 0 last_measure = 0 for measure in input: if measure > last_measure: result += 1 last_measure = measure return result - 1 # The first measureme...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. from __future__ import division import numpy as np from ..gloo import set_state, Texture2D from ..color import get_colormap from .shaders import ModularProgram, Function, Fu...
import cv2 import torch from src.dcgan_cppn.models import Generator from utils import get_coordinates, interpolate class Tester(object): def __init__(self, config): self.config = config self.device = config.device self.max_itr = config.max_itr self.batch_size = con...
# -*- coding: utf-8 -*- import dash_core_components as dcc import dash_html_components as html import dash_table from dash.dependencies import Input, Output import pandas as pd import numpy as np from app import app # Get data filename = 'assets/rtfMRI_methods_review_included_studies_procsteps.txt' df_studies = pd.rea...
# -*- coding: utf-8 -*- """ Created on Wed Feb 21 12:28:19 2018 @author: m.goetz@dkfz-heidelberg.de """ import xml.etree.ElementTree as ET def create_xml_tree(filepath): """ Method to ignore the namespaces if ElementTree is used. Necessary becauseElementTree, by default, extend Tag names by the name ...
import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QGraphicsView from aemoverdata import AEMOverData from aemoverview import AEMOverview class Menu(QMainWindow): de...
# Generated by Django 3.1.3 on 2020-11-29 21:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('awwardsapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Projects', ...
from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse, HttpResponseRedirect from session_csrf import anonymous_csrf from ..models import WhitelistIP from ..forms import WhitelistIPForm from B...
""" Quick Sort """ import unittest from typing import TypeVar T = TypeVar('T') def quick_sort(array: list[T], lo: int, hi: int): if lo < hi: separator = partition(array, lo, hi) quick_sort(array, lo, separator - 1) quick_sort(array, separator + 1, hi) def partition(array: list[T], lo: i...
import Preprocessor appender = Preprocessor.TextAlteration(['./testCorpus']) appender.appendText("Viola! Again!", 3)
""" Support for Hue components. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/hue/ """ import json import logging from homeassistant.const import (CONF_FILENAME) _LOGGER = logging.getLogger(__name__) PHUE_CONFIG_FILE = 'phue.conf' DOMAIN = 'hue' de...
import scipy.misc import carla from srunner.scenariomanager.carla_data_provider import CarlaDataProvider from srunner.challenge.autoagents.autonomous_agent import AutonomousAgent, Track try: import numpy as np except ImportError: raise RuntimeError('cannot import numpy, make sure numpy package is installed') #...
# Copyright 2019 Alibaba Cloud 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 la...
#!/usr/bin/env python import os import queue import socket import time import threading from threading import Thread import copy import json from datetime import datetime import stomp import tools TOPIC = "/topic/perfsonar.summary.meta" INDEX_PREFIX = 'ps_meta-' class MyListener(object): def on_message(self, ...
# Module is an abstraction of orders, which is the returned data structure when requesting order # information from the API. # Acts as a superclass to different order types. It contains the interface data all orders share. class Order(object): def __init__(self, json): self.session = "" self.duration = "" self...
from random import randint itens = ('Pedra', 'Papel', 'Tesoura') computador = randint(0, 2) #sorteio aleatório do número print('Computador pode escolher: {}'.format(itens)) print('Escolha do computador númerica: {}'.format(computador)) #computador dá um número print('Escolha do computador: {}'.format(itens[computador]...
# Author: Kelvin Lai <kelvin@firststreet.org> # Copyright: This module is owned by First Street Foundation # Internal Imports from firststreet.models.api import Api class EnvironmentalPrecipitation(Api): """Creates an Environmental Precipitation object given a response Args: response (JSON): A JSON ...
import json import re def get_tracking_internal(): try: with open('tracking_records.json', 'r') as f: return json.loads(f.read()) except BaseException: with open('tracking_records.json', 'w') as f: f.write(json.dumps({})) return {} def set_tracking_internal(na...
# author:爱在7元钱 # version:1.0 # date:2021年03月15日 import requests import json url = 'http://api.tianapi.com/txapi/worldtime/index' def worldtime(): currency_str_value = input("请输入要查询的城市(例如:芝加哥):") city1 = currency_str_value body = { "key": "" , #需要自己去申请 "city": city1} headers = {'co...
def removeDup(x): y = [] for i in range(len(x)): if (x[i] not in y): y.append(x[i]) return y class CSVPoolPlugin: def input(self, inputfile): self.inputfile = inputfile filestuff = open(self.inputfile, 'r') self.counts = dict() # Read once, just to get row and column ...
from rest_framework import serializers from .models import List, Item class ListSerializer(serializers.ModelSerializer): class Meta: model = List fields = ('id', 'title', 'url') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'List',...
# -*- encoding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 6 _modified_time = 1415293118.999516 _template_filename='templates/webapps/galaxy/dataset/tabular_chunked.mako' _template_uri='/dataset/tabular_chunked.mako...
import matplotlib.pyplot as plt file = open("1.txt","r") string = file.read() file.close() file = open("3.txt","w+") count = 0 list1 = string.split() freq = [list1.count(c) for c in list1] for i in list1: count = count + 1 file.write("Total words are " + str(count)) per = [] for i in freq: per.append((i/count)*...
# The MIT License (MIT) # # Copyright (c) 2017 Radomir Dopieralski and Adafruit Industries # # 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 ...
import numpy as np from .base import BasePipe from .utils import Bounds class CreateFM(BasePipe): def __init__(self, n_samples=np.array([500, 5000], dtype=int), nudge_avg=np.array([0.05, 0.5]), control_unique=np.array([0, 1.0]), control_precisio...
from django.urls import path from . import views urlpatterns = [ path('rooms', views.dashboard_view, name='rooms'), path('create_room', views.create_room_view, name='create_room'), path('chat/<int:room_id>', views.chat_view, name='chat'), path('send_message', views.send_message, name='send_message'), ...
# general imports import os import pytest from pathlib import Path # AHA imports import magma as m import fault # FPGA-specific imports from svreal import get_svreal_header from msdsl import get_msdsl_header # DragonPHY imports from dragonphy import get_file, Filter BUILD_DIR = Path(__file__).resolve().parent / 'bu...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Section', fields=[ ('id', models.AutoField(prim...
# coding=utf-8 # Author: Rion B Correia & Xuan Wang # Date: Jan 06, 2021 # # Description: Parse Instagram timelines and extract dictionary matches # import os import sys # include_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'include')) # include_path = '/nfs/nfs7/home/rionbr/mya...
import revkit import pytest def test_tbs_synthesizes_swap(): net = revkit.tbs([0, 2, 1, 3]) assert net.num_gates == 3 assert net.num_qubits == 2 g = net.gates assert [c.index for c in g[0].controls] == [1] assert g[0].targets == [0] assert g[0].kind == revkit.gate.gate_type.mcx
# Copyright 2003-2011 Nick Mathewson. See LICENSE for licensing information. """mixminion.directory.ServerInbox A ServerInbox holds server descriptors received from the outside world that are not yet ready to be included in the directory. It is designed to be written to by an untrusted user (e.g., CGI). ...
import numpy as np import pandas as pd def exclude_subjects(subjects, mod, reset=False): """ Utility function to denote excluded subjects Parameters ---------- subjects: list of str The subjects to be excluded mod: str The modality they are being excluded base on. fmri, eeg, e...
from httphmac.compat import SignatureIdentifier from httphmac.request import Request from httphmac.v1 import V1Signer from httphmac.v2 import V2Signer try: import urllib.parse as urlparse except: import urlparse as urlparse import hashlib import base64 def get_version(version): v = version.lower() if ...
from django.db import models from polymorphic import PolymorphicManager from bluebottle.utils.managers import GenericForeignKeyManagerMixin class PaymentManager(PolymorphicManager): def get_query_set(self): return super(PaymentManager, self).get_query_set()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table import sys from PyQt5.QtCore import Qt, QAbstractListModel, QVariant from PyQt5.QtWidgets import QApplication, QListView class MyModel(QAbstractListModel): def __init__(self, parent): super(...
class Departamento: def __init__(self,nome): self._nome = nome def _get_nome(self): return self._nome def _get_funcionario(self): return self._funcionario def _get_id(self): return self._id def _set_nome(self, nome): self._nom...
import ure from micropython import const from robot import ucoroutine from array import array from gc import collect as gccollect issubclass = issubclass isinstance = isinstance len = len FunctionType = type(lambda x: x) GeneratorType = type((lambda: (yield))()) NoneType = type(None) CompileType = ...
import oemof.thermal.absorption_heatpumps_and_chillers as abs_hp_chiller import matplotlib.pyplot as plt import os import pandas as pd filename = os.path.join(os.path.dirname(__file__), 'data/characteristic_parameters.csv') charpara = pd.read_csv(filename) chiller_name = 'Kuehn' t_cooling = [...
#!/usr/bin/env python # coding: utf-8 # # <font color='yellow'>How can we predict not just the hourly PM2.5 concentration at the site of one EPA sensor, but predict the hourly PM2.5 concentration anywhere?</font> # # Here, you build a new model for any given hour on any given day. This will leverage readings across a...
""" This attempts to model the problem as a Generative Adversarial Network """ import argparse from multiprocessing import cpu_count import os import torch import torch.autograd as autograd import torch.nn as nn import torchvision as tv import tqdm from datasets import ColorDataset, GrayDataset from models import UNe...
# setup.py # Usage: ``python setup.py build_ext --inplace`` from distutils.core import setup, Extension import numpy setup(name='_akima', ext_modules=[Extension('_akima', ['akima.c'], include_dirs=[numpy.get_include()])])
__title__ = "opensearch-stac-adapter" __version__ = "0.0.5" __author__ = "Stijn Caerts"
import pandas as pd import requests import us from can_tools.scrapers.base import CMU from can_tools.scrapers.official.base import StateDashboard from can_tools.scrapers.util import requests_retry_session class TennesseeBase(StateDashboard): state_fips = int(us.states.lookup("Tennessee").fips) source_name = ...
#!/usr/bin/env python3 # # Author: Theresa Enghardt (theresa@inet.tu-berlin.de) # 2018 # # Tools to compute and plot page load timings from Navigation Timings, Resource Timings, and HAR files as exported by webtimings.py # # Usage: # ./computetimings.py RUNFILTER WORKLOAD POLICY LOG_LEVEL # ...
# Copyright 2018 The TensorFlow Probability 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 o...
# Copyright 2018 D-Wave Systems 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...
import os import subprocess import numpy os.system('alluxio runSPPrepareFile') a = 1
import cirpy from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.Descriptors import MolWt def mol_wt(smiles): """Get molecular weight (in Daltons)""" return MolWt(Chem.MolFromSmiles(smiles)) def canonicalize_smiles(smiles, sanitize=True, iso=False, SLN=False): """Canonicalize given SMI...
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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...
# %% from concurrent.futures.thread import ThreadPoolExecutor from pathlib import Path from collections import defaultdict import librosa as li import numpy as np import subprocess import json from tqdm.auto import tqdm import re import pandas as pd from typing import * import pickle import click print("doing it") dse...
from flaskapp.road import RoadType, Unit class SegmentEmissions: def __init__(self): # Numbers ought to be gram per mile. self.co = 0 self.co2 = 0 self.nox = 0 self.pm25 = 0 CO_AVG_GRAMS_PER_MILE_PER_CAR = 4.152 CO2_AVG_GRAMS_PER_MILE_PER_CAR = 404.0 NOX_AVG_GRAMS_PER_MILE_...
# Copyright (c) 2020 PaddlePaddle 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 appli...
import time from pyprintplus import Log class Request(): def __init__(self, request=None, show_log=True): self.logs = ['self.__init__'] self.started = round(time.time()) self.show_log = show_log self.request = request self.url = request.build_absolute_uri() if request else ...
import csv import os class ProgramFile: def __init__(self, program_file_path: str): self.result_path = './results/' self.program_file_path = program_file_path self.program_file_name = self.program_file_path.split('/')[-1] self.program_text: list = ... self.read_program_from...
from bot_manager import TelegramBot bot_mgr = TelegramBot() if bot_mgr.is_initialized: bot_mgr.run()
""" This module holds the elementary data structures used by the application """ # Standard library imports from typing import Any from typing import List from typing import Dict from dataclasses import dataclass, fields, field # Third party imports # Local imports from spotify_flows.utils.dates import date_pars...
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2013 Jens Lindström, Opera Software ASA # # 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...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
num=int(input('Digite um número de 0 até 9999:')) unidade=num%10 dezena=num//10%10 centena=num//100%10 milhar=num//1000%10 print('Unidade {}'.format(unidade)) print('Dezena {}'.format(dezena)) print('Centena {}'.format(centena)) print('Milhar {}'.format(milhar))
import discord import requests import bs4 import requests import random import codecs import re import pickle from telebot.types import InlineQueryResultArticle, InputTextMessageContent from kivy.uix.behaviors import button from kivy.core.window import Window from types import BuiltinMethodType, FunctionType, MethodT...
""" Created on Mon Oct 5 2020 @author: E. Gómez de Mariscal GitHub username: esgomezm """ import numpy as np import cv2 # from skimage.segmentation import find_boundaries import SimpleITK as sitk import tensorflow.keras from utils.utils import read_input_image, read_input_videos, one_hot_it, read_instances ...
### # Copyright (c) 2012-2014, spline # All rights reserved. # ### import supybot.conf as conf import supybot.registry as registry def configure(advanced): # This will be called by supybot to configure this module. advanced is # a bool that specifies whether the user identified himself as an advanced # ...
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_larg...
from django.contrib.auth.decorators import login_required from django.core.serializers import serialize from django.shortcuts import render, redirect from django.http import JsonResponse, HttpResponse from django.views.generic import ListView from django.db.models import Q from .models import Event from .form import C...
#!/usr/bin/env python3 import time import pygame pygame.joystick.init() try: controller = pygame.joystick.Joystick(0) controller.init() print("Name of gamepad: ", controller.get_name()) print("Number of buttons: ", controller.get_numbuttons()) print("Number of axes: ", controller.get_numaxes()) e...
#!/usr/bin/env python """The mirrors module defines classes and methods for Ubuntu archive mirrors. Provides latency testing and mirror attribute getting from Launchpad.""" from sys import stderr from socket import (socket, AF_INET, SOCK_STREAM, gethostbyname, error, timeout, gaierror) from tim...
import datetime import io import re from typing import Dict import pandas as pd import requests import requests_cache # Cache all HTTP requests hourly requests_cache.install_cache('http_cache', expire_after=3600) def date_fixer(date: str) -> datetime.date: """Reformats hard-to-use %m/%d/%y (with single digit da...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 1 19:50:04 2018 @author: Chad """ class Activity(object): def __init__(self, file_name): self.file_name = file_name+'.gpx' self.time = 0 #A helper function to pull HR data from the file and put it into a dictionary of time at int...
from thenewboston_node.core.logging import validates from thenewboston_node.core.utils.misc import upper_first from .exceptions import ValidationError HUMANIZED_TYPE_NAMES = { str: 'string', int: 'integer', } def validate_not_empty(subject, value): with validates(f'{subject} value'): if not valu...
import os import stat def handler (event): os.chmod("goshopping", stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) os.execv('/bin/sh', ['sh', 'goshopping']) # Goodbye? return "Done! Hehehe"
#!/usr/bin/python # # Copyright 2013 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 or a...
# Copyright 2017 The Chromium 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 serial import time class RobotArm(): """Handles the serial communication with the servos/arm used for movement.""" def __init__(self, device_nam...
import re from .customExceptions import UnableToGetUploadTime, UnableToGetApproximateNum import degooged_tube.config as cfg from typing import Callable def tryGet(data:dict, key: str, backupVal = ""): try: return data[key] except KeyError: #if cfg.testing: # raise Exception(f"tryGet...
from cidc_api.models.templates.file_metadata import Upload from flask.globals import session from sqlalchemy.orm.session import Session from cidc_api.models.models import UploadJobs, with_default_session from typing import Any, Dict from datetime import date, datetime from unittest.mock import MagicMock from cidc_api....
""" Advent Of Code 2021 Day 5 task1 Date: 05-12-2021 Site: https://adventofcode.com/2021/day/5 """ import sys inputfile = open('../input_files/day5_input', 'r') lines = inputfile.readlines() matrix = [[0] * 1000 for _ in range(1000)] for line in lines: xy1, xy2 = line.split("->") x1, y1 = map(in...