content
stringlengths
5
1.05M
import sys import requests import csv import json from mmda.types.annotation import SpanGroup, BoxGroup from mmda.types.document import Document pdf_file = sys.argv[1] with open(pdf_file,"rb") as f: pdf_bytes = f.read() doc = Document.from_json(requests.post("http://symbolscraper", data = pdf_bytes).json()) res...
""" CamPy: Python-based multi-camera recording software. Integrates machine vision camera APIs with ffmpeg real-time compression. Outputs one MP4 video file and metadata files for each camera "campy" is the main console. User inputs are loaded from config yaml file using a command line interface (CLI) configu...
import unittest import subprocess import os import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) cleanup_pycs = os.path.join(TOPDIR, 'cleanup_pycs.py') class Tests(unittest.TestCase): def test_cleanup_pycs(self): """Test cleanup_pycs.py script""" with utils.TempDi...
import re texto = "En esta cadena se encuentra una palabra mágica" re.search('mágica', texto) re.search('hola', texto) palabra = "mágica" encontrado = re.search(palabra, texto) if encontrado: print("Se ha encontrado la palabra:", palabra) else: print("No se ha encontrado la palabra:", palabra)
v1 = int(input()) v2 = int(input()) v3 = int(input()) if v2 > v1: pass
import numpy as np import matplotlib.pyplot as plt import BotDecidesPos #import matplotlib.pyplot as plt class BotPool: recorder=[] def __init__(self): pass def register(self,nbot): self.recorder.append((nbot)) print(nbot.id,"has been registered") def getList(sel...
from ..input_action import InputAction class ButtonAdd(InputAction): def run(self, total, game): addition = self._value applicables = ['add','subtract','multiply','divide','append'] def addValue(actionName): action = game.actions[actionName] typeCheck = str(type(act...
# -*- coding: utf-8 -*- import functools from typing import Optional import cytoolz import structlog from ..typedefs import BatchJrpcRequest from ..typedefs import CachedBatchResponse from ..typedefs import CachedSingleResponse from ..typedefs import SingleJrpcRequest from ..typedefs import SingleJrpcResponse from .t...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df=pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv') df.columns # Mean, median and min sales by country df.pivot_table(index=['Country'], values=['Sales'], aggfunc={'median','mean','min'})...
#!/usr/bin/python3 # ***************************************************************************** # # 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 ...
# -*- coding: utf-8 -*- """ Provides a way to introspect database and returns its current state for: - schemas - sequences - tables - views - triggers - indices - constraints Usage example: .. code-block:: ipythonconsole In [1]: uri='postgresql://localhost/jukoro_test.ju_20150403102042' In [2]: from jukoro...
def outer(func): def inner(*args, **kwargs): print("My message") return func(*args, **kwargs) return inner @outer def div(a, b): return a / b print(div(1, 2))
# Generated by Django 3.1 on 2020-09-29 21:48 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('app', '0026_auto_20200930_0117'), ] operations = [ migrations.AlterField( model_name='jumbotron', name='...
import torch from torch.distributions import HalfCauchy, HalfNormal import torch.nn.functional as F import matplotlib.pyplot as plt from tqdm import tqdm from pyro.distributions import * import pyro from pyro.optim import Adam from pyro.infer import SVI, Trace_ELBO, Predictive assert pyro.__version__.startswith('...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next ''' https://leetcode.com/problems/merge-two-sorted-lists/discuss/9735/Python-solutions-(iteratively-recursively-iteratively-in-place). 1. Iterative 1. Start with fir...
# coding=utf-8 from app import create_app, db, cli from app.models import Thumbnail, Image, Currency, Event, EventCurrency, Post, Expense, Settlement, User, Message, Notification, Task app = create_app() cli.register(app) @app.shell_context_processor def make_shell_context(): return {'db': db, 'Thum...
#!/usr/bin/python -u """ Copyright (C) 2017 Jacksgong(jacksgong.com) 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...
print(max(i*j for i in range(100,1000) for j in range(100,1000) if str(i*j) == str(i*j)[::-1]))
def compute(n): # function sent to remote nodes for execution time.sleep(n) return n if __name__ == '__main__': import dispy # list remote nodes (here Amazon EC2 instance with external IP 54.204.242.185) nodes = ['54.204.242.185'] # use ssh to forward port 51347 for each node; e.g., # 'ssh ...
from enemy import * from Dragon import * import Message import enemy # The dragon is a special and unique enemy, hence these values are hardcoded class Drake(Dragon): def __init__(self, messageLog, currentMap = None): super().__init__(messageLog, currentMap) self.name = "Drake" self.levelM...
import os import asobann import asobann.app import pytest from flask import Flask pytestmark = [pytest.mark.quick] PARAMS = [ { 'id': 'development', 'input': { 'FLASK_ENV': 'development', 'env': { }, }, 'expected': { 'config': { ...
import numpy as np from multiprocessing import Pool, Process import time def f(x): time.sleep(2) return x*x def rand(): return np.random.random() def run_map(numW=4, numJobs=20): t1= time.time() pool = Pool(numW) print(pool.map(f, range(numJobs))) t2 = time.time() print('Time: ', t2 - t1) def run_process(n...
from pytest import fixture from livedivulgador.bots.livedivulgador import LiveDivulgador from livedivulgador.plugins.twitter import TwitterPlugin @fixture def livedivulgador(): plugins_list = [TwitterPlugin] bot = LiveDivulgador() bot.add_plugins(plugins_list) yield bot del bot def test_live...
import sys, getopt, signal, threading, serial from time import sleep from functools import partial from lib import xpc # get_params param_port = 'COM3' param_baud = 9600 stop_threads = False client_xplane = None def get_params(): global param_port global param_baud strUsage = 'usage: ArdSerialUDP.py --por...
#!/usr/bin/env python3 try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='Medinfore', version='1.1.0', description='Indexing and searching engine in a medical corpus', author='Michael Domingues', author_email='dominguesjust@gmail.com', ...
import os import json import time import numpy as np import pandas as pd import shappack from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA, KernelPCA ## Parameters ################################################### FILE_PATH = "./data/2021-08-18-argowf-chaos-b2qdj-user_pod-memory-...
# https://stackoverflow.com/questions/30135091/write-thread-safe-to-file-in-python from threading import Thread from thread_writer import ThreadWriter from pydng.core import RPICAM2DNG import document_handler class ThreadRawConverter: def __init__(self, config, stream, filename): self.config = config ...
#!/usr/bin/env python2 import math import sys import random if len(sys.argv) < 7: print "Usage: %s num spread n_find n_insert n_delete n_range [seed]" % sys.argv[0] exit(1) n = int(sys.argv[1]) spread = int(sys.argv[2]) find = int(sys.argv[3]) insert = int(sys.argv[4]) delete = int(sys.argv[5]) rng = int(sys...
poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' # The above phrase is used to input text in the file poem.txt which # goes to the default directory \exercies in this case # Open for 'w'riting f = open('poem.txt', 'w') # Write text, which is the string...
from cqc.pythonLib import CQCConnection import sys import time sys.path.append("../..") from backends.cqc_backend import CQCBackend from components.host import Host from components.network import Network from objects.qubit import Qubit import components.protocols as protocols def main(): backend = CQCBackend() ...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from unittest import TestCase from uw_sws_graderoster.dao import SWS_GradeRoster_DAO class SWSGradeRosterTestDao(TestCase): def test_custom_headers(self): self.assertEquals( SWS_GradeRoster_DAO()._custom_he...
import requests from bs4 import BeautifulSoup from datetime import datetime from webapp.db import db from webapp.news.models import News def get_html(url): try: result = requests.get(url) result.raise_for_status() return result.text except(requests.RequestException, ValueError): ...
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import sys import os import optparse import cPickle as pickle import numpy as np def get_options(): parser = optparse.OptionParser() parser.add_option("--root", default='regr_vals', ...
import time import os def check_line(line: str): stack = [] opening = {"(": 1, "[": 2, "{": 3, "<": 4} closing = {")": ("(", 3), "]": ("[", 57), "}": ("{", 1197), ">": ("<", 25137)} for i, char in enumerate(line): if char in opening: stack.append(char) else: pop...
from typing import DefaultDict import tensorflow as tf import numpy as np import pytest from bard.midi import tokenizer, vocabulary MAX_SIZE = 1000 DEFAULT_DECODED = '0' @pytest.mark.parametrize("inputs, expected", [ (["a", "a", "b", "c", "a", "d", "f"], 5), (["a", "b", "c", "d", "e", "f"], 6), ]) def test_tok...
# sv2020.04.07 # # class Cross_Entropy() # Compute cross entropy across each feature for feature selection # # three methods included # compute: # Manimaran A, Ramanathan T, You S, et al. Visualization, Discriminability and Applications of Interpretable Saak Features[J]. 2019. # KMeans_Cross_Entropy impo...
# # This file is part of pyasn1-modules software. # # Created by Russ Housley. # # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # # X.509v3 Certificates for Secure Shell Authentication # # ASN.1 source from: # https://www.rfc-editor.org/rfc/rfc6187.txt # from pyasn1.type i...
from JumpScale import j import os def _setup_stacktrace_hook(): '''Set up SIGUSR2 signal handler which dumps stack traces of all threads''' try: import signal except ImportError: # No signal support on current platform, ignore return sig = signal.SIGUSR2 def stderr(): ...
"""The organization command.""" from json import dumps from .base import Base from bonita.api.bonita_client import BonitaClient class Organization(Base): """Manage organization""" def run(self): #print('You supplied the following options:', dumps(self.options, indent=2, sort_keys=True)) # b...
# bdateutil # --------- # Adds business day logic and improved data type flexibility to # python-dateutil. 100% backwards compatible with python-dateutil, # simply replace dateutil imports with bdateutil. # # Author: ryanss <ryanssdev@icloud.com> # Website: https://github.com/ryanss/bdateutil # License: MIT (s...
from django.urls import path from .schema import schema from .views import AsyncGraphQLView urlpatterns = [path("graphql", AsyncGraphQLView.as_view(schema=schema))]
# # This file is part of the FFEA simulation package # # Copyright (c) by the Theory and Development FFEA teams, # as they appear in the README.md file. # # FFEA is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software ...
""" User interface Controls for the layout. """ from __future__ import unicode_literals from pygments.token import Token from abc import ABCMeta, abstractmethod from collections import defaultdict, namedtuple from six import with_metaclass from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER from prompt_too...
# ------------------------------------------------------------------------ # BoxeR # Copyright (c) 2022. All Rights Reserved. # Licensed under the MIT License [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from mmf (https://github.com/facebookresearch/mmf...
import copy import numpy as np from State import State from Player import Player class Environment: def __init__(self, NUM_ROWS, NUM_COLS, DEPTH, init_board=None): self.state = None self.moves_made = set() self.duplicate_moves = set() self.draw_flag = False self.turn = None ...
#!/usr/bin/env python3 # encoding: UTF-8 """ This file is part of IPGeoLocation tool. Copyright (C) 2015-2016 @maldevel https://github.com/maldevel/IPGeoLocation IPGeoLocation - Retrieve IP Geolocation information Powered by http://ip-api.com This program is free software: you can re...
import time from multiworld.core.image_env import ImageEnv from rlkit.core import logger from rlkit.envs.vae_wrapper import temporary_mode import cv2 import numpy as np import os.path as osp import os from rlkit.samplers.data_collector.vae_env import ( VAEWrappedEnvPathCollector, ) from rlkit.torch.her.her import...
from struct import pack class Packet: """robot packet type""" PACKET_LEN = 20 PAYLOAD_LEN = 16 def __init__(self, dev, cmd, inc, payload=bytes(PAYLOAD_LEN), crc=None): self.dev = dev self.cmd = cmd self.inc = inc assert len(payload) <= self.PAYLOAD_LEN, "invalid paylo...
import unittest from .. import keystore, networks class TestBip44Derivations(unittest.TestCase): def setUp(self): self.initial_net = networks.net def tearDown(self): # make sure we restore the network settings, in case it affects other tests if self.initial_net == networks.MainNet: ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
""" `gef` command test module """ import pytest import pathlib from tests.utils import ( gdb_run_cmd, GefUnitTestGeneric, gdb_start_silent_cmd_last_line, removeuntil, ) class GefCommand(GefUnitTestGeneric): """`gef` command test module""" def test_cmd_gef(self): res = gdb_run_cmd("...
from netapp.netapp_object import NetAppObject class TestViewType1(NetAppObject): """ Test input typedef 1 """ _node = None @property def node(self): """ Node Attributes: key, required-for-create, non-modifiable """ return self._node @node.setter ...
"""Drop the response column. We're gonna push straight to Bas. Revision ID: 04d56b17edad Revises: 60a4bfee242f Create Date: 2020-12-11 08:26:57.780808 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '04d56b17edad' down_revision = '60a4bfee242f' branch_labels = ...
"""Plot figures for tutorial.""" import chaospy as cp import numpy import matplotlib.pyplot as plt import seaborn def plot_figures(): """Plot figures for tutorial.""" numpy.random.seed(1000) def foo(coord, param): return param[0] * numpy.e ** (-param[1] * coord) coord = numpy.linspace(0, 10...
import numpy as np import torch class EvaluationMetrics: def __init__(self): self.relu = torch.nn.ReLU() def average_precision_score(self, bbox, bbox_pred, threshold): iou_scores = self.iou_loss(bbox, bbox_pred) y_true = np.ones(bbox.size()[0]) y_loss = self.iou_loss(bbox, bbox...
from dataclasses import dataclass, field from typing import List, Optional @dataclass class Ids: class Meta: name = "ids" idref: List[str] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, } )...
# Generated by Django 2.2.19 on 2021-04-08 10:13 import django.contrib.postgres.fields.jsonb import django.db.models.deletion import django_extensions.db.fields from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '002...
# Generated by Django 2.2.4 on 2020-12-04 05:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Dashboard', '0015_recomm...
from django.contrib import admin from Pins.models import Pin admin.site.register(Pin)
#! /usr/bin/env python2 # # This source file is Copyright (c) 2019, FERMI NATIONAL ACCELERATOR # LABORATORY. All rights reserved. # For details of the Fermitools (BSD) license see COPYING. import cvmfs_user_pub def application(environ, start_response): return cvmfs_user_pub.dispatch(environ, start_response)
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from pandora.impl.pytorch import utils class RNNEncoder(nn.Module): """RNN Character level encoder of the focus token""" def __init__(self, num_layers, input_size, hidden_size, dropout=0.0, ...
#!/usr/bin/env python # coding: utf-8 # # **Hello, World!** # Welcome to the world of python. In this section, we simply print a string using python code. You can say it's kind of a ritual/tradition for anyone who sets on a journey in coding with any language - our way of saying "Hey world, here I come!" 😉 # In[1]...
#!/usr/local/bin/python2.7 from sys import exit from os import environ, system environ['KERAS_BACKEND'] = 'tensorflow' environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" environ["CUDA_VISIBLE_DEVICES"] = "" import numpy as np from subtlenet import config, utils from subtlenet.backend import obj from subtlenet.generator...
import hashlib from front_end.grpc import assignService_pb2 ''' This class represents a Region which contains the size of the region and finger prints contained in it. ''' class Region: def __init__(self, max_size: int): self.max_size = max_size self.current_size = 0 self.fingerprints...
"""The scripts will produce a pandas `DataFrame` which contains information about which combinations of environments have which data types. """ import itertools import logging import os from collections import defaultdict import pandas from evaluator.properties import ( Density, EnthalpyOfMixing, EnthalpyO...
import board import terminalio from adafruit_display_text import label display = board.DISPLAY # Set text, font, and color text = "HELLO WORLD" font = terminalio.FONT color = 0x0000FF # Create the tet label text_area = label.Label(font, text="HELLO WORLD", color=0x00FF00) # Set the location text_area.x = 100 text_a...
airport_codes = {"AAL": "Aalborg, Denmark", "AES": "Aalesund, Norway", "AAR": "Aarhus, Denmark", "YXX": "Abbotsford, BC, Canada", "YXX": "Abbotsford, BC, Canada", "ABZ": "Aberdeen, Scotland", "ABR": "Aberdeen, SD, USA"...
from django import template register = template.Library() @register.simple_tag def get_lessons_names(course, module_name): module = course.modules.filter(name__exact=module_name) return [lesson.name for lesson in module.lessons.all()]
import pickle import zlib from pathlib import Path from typing import Any from app.osm.pbf.blob_meta import BlobMeta from app.osm.pbf.osm_pb2 import Blob def read(filepath: Path) -> Any: with filepath.open(mode='rb') as file: return pickle.load(file) def write(content: Any, filepath: Path) -> Any: ...
class GithubRepo: pass # def __init__(self, root_path, defaults=None): # dict.__init__(self, defaults or {}) # self.root_path = '' def scan(self, repo): return self def exists(self): return False
#! /usr/bin/env python import signal # Flask from flask import Flask, render_template, flash, request from flask_socketio import SocketIO, emit from collections import namedtuple from ml_thread import MLThread from udp_thread import UDPThread __FADE__=False # Generates a flask app that lets you type to interact def ...
# -- Read command line args -- # argparse guidance: https://docs.python.org/3/library/argparse.html import argparse parser = argparse.ArgumentParser(description='Update external dependencies.') parser.add_argument('--verbose', help='chatty output', action='store_true') args = parser.parse_args() from devops_spt impo...
from utils import * class FeatureMem: def __init__(self, n_k, u_emb_dim, base_model, device): self.n_k = n_k self.base_model = base_model self.p_memory = torch.randn(n_k, u_emb_dim, device=device).normal_() # on device u_param, _, _ = base_model.get_weights() self.u_memory...
""" Handles reading the session cookie. """ import datetime import json from bottle import local, request, response from codalab.server.authenticated_plugin import user_is_authenticated class LoginCookie(object): """ Represents the user's session cookie after logging in. """ KEY = "codalab_session"...
from JDI.core.settings.jdi_settings import JDISettings from JDI.web.selenium.elements.api_interact.find_element_by import By from JDI.web.selenium.elements.common.text import Text from JDI.web.selenium.elements.complex.table.cell import Cell from JDI.web.selenium.elements.complex.table.columns import Columns from JDI.w...
# -*- coding: utf-8 -*- import os from django.core.urlresolvers import reverse from seaserv import seafile_api from seahub.test_utils import BaseTestCase class ListPrivSharedFoldersTest(BaseTestCase): def tearDown(self): self.remove_repo() def test_can_list_priv_shared_folders(self): repo_id...
"""Forwards call to setuptools.setup() after parsing: * name from package folder * long description from README.rst * packages from setuptools.find_packages() * dependencies from requirements.txt * remaining properties from package-level package.json """ import os import json from setuptools import setu...
from pathlib import Path from torch.utils.data import Dataset, ConcatDataset, DataLoader, distributed from torchvision import transforms as trans from torchvision.datasets import ImageFolder from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import numpy as np import cv2 import bcolz import pickle ...
from protocols.migration import MigrateReports500To600, BaseMigration from protocols.migration.base_migration import BaseMigrateReports500And600 from protocols.protocol_6_1 import reports as new_model from protocols.protocol_7_0 import reports as old_model from protocols.protocol_7_0.reports import diseaseType, TissueS...
# -*- coding: utf-8 -*- # code for console Encoding difference. Don't mind on it import sys import imp imp.reload(sys) try: sys.setdefaultencoding('UTF8') except Except as E: pass import testValue from closedown import CloseDown, CloseDownException closedownChecker = CloseDown(testValue.LinkID,testValue.SecretKey) ...
import logging import os from collections import namedtuple import threading from du.gerrit.Utils import Utils as GerritUtils from du.utils.ShellCommand import ShellCommand, CommandFailedException from du.gerrit.rest.change.ChangeEndpoint import ChangeEndpoint from du.gerrit.ssh.Connection import Connection from du.ge...
# -*- coding: utf-8 -*- """ @date: 2020/3/4 下午4:00 @file: custom_classifier_dataset.py @author: zj @description: 分类器数据集类,可进行正负样本集替换,适用于hard negative mining操作 """ import numpy as np import os import cv2 from PIL import Image from torch.utils.data import Dataset from torch.utils.data import DataLoader import torchvisi...
from direct.directnotify import DirectNotifyGlobal from toontown.cogdominium.DistCogdoGameAI import DistCogdoGameAI import CogdoMazeGameGlobals from direct.distributed.ClockDelta import * from direct.task import Timer from toontown.battle import BattleBase from toontown.building.ElevatorConstants import * GAME_DONE_DEL...
from sanic.exceptions import abort def test_sanic_abort_401(app): sanic_app, _ = app @sanic_app.route("/abort") async def abort_request(request): abort(401) _, response = sanic_app.test_client.get("/abort") assert response.status == 401 # TODO test issue #93
"""General-purpose test script for image-to-image translation. Original code: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/test.py Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from '--checkpoints_dir' and save the results ...
def guess_number(): answer=None our_number=21 while answer != our_number: answer=int(raw_input('guess me')) if answer == our_number: print "correct" return elif answer > our_number: print "no, higher" else: print "no, lower" ...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Job entity classes. """ from everest.entities.base import Entity from thelma.entities.iso import ISO_STATUS from thelma.entities.iso import IsoJobPreparation...
import csv file=open("student.csv","w",newline="") fwriter=csv.writer(file) fwriter.writerow(["rollno","name","marks"]) for i in range(5): print("Student Record",i+1) rollno=int(input("Enter rollno:")) name=input("Enter Name:") marks=float(input("Enter Marks:")) record=[rollno,name,marks] fwrite...
"""Test the LED device.""" from mpf.core.rgb_color import RGBColor from mpf.tests.MpfTestCase import MpfTestCase, test_config class TestDeviceLight(MpfTestCase): def get_config_file(self): return 'light.yaml' def get_machine_path(self): return 'tests/machine_files/light/' def test_defau...
from utils import read_file def calc_fuel(mass): return mass // 3 - 2 def calc_fuel_recursive(mass): total = 0 res = calc_fuel(mass) while res > 0: total += res res = calc_fuel(res) return total print("#--- part1 ---#") assert(calc_fuel(12) == 2) assert(calc_fuel(14) == 2) ass...
import torch import torch.nn as nn import torch.nn.functional as F import logging import sys logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) class TabularNet(nn.Module): def __init__(self, n_cont, n_cat, emb_sz = 100, dropout_p = 0.1, layers...
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from .utils import find_indentation from lib2to3.pgen2 import token from lib2to3.pygram import python_symbols as symbols from .utils import (get_whitespace_before_definition, has_parent, tuplize_comments) class FixBlankLines(BaseFix):...
from setuptools import setup, find_packages setup( name="peinfo", version="2.0.0", author="Marcus LaFerrera (@mlaferrera)", url="https://github.com/PUNCH-Cyber/stoq-plugins-public", license="Apache License 2.0", description="Gather relevant information about an executable using pefile", pac...
# Copyright (c) 2017, John Skinner import typing import bson import pymodm.fields as fields from pymodm.context_managers import no_auto_dereference from arvet.database.autoload_modules import autoload_modules from arvet.core.image_source import ImageSource from arvet.batch_analysis.task import Task from arvet.config.pa...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('login', '0014_auto_20160707_1625'), ] operations = [ migrations.AddField( model_name='userprofile', ...
import re import time import pytest from freiner.storage import MovingWindow from freiner.strategies.fixed_window import FixedWindowRateLimiter from freiner.strategies.moving_window import MovingWindowRateLimiter def test_pluggable_storage_fixed_window(): class MyStorage: def incr(self, key: str, expiry...
# Importing the pickle library import pickle # Dumping the model object to save it as model.pkl file pickle.dump(model, open('model.pkl', 'wb+'))
import discord from discord.ext import commands class Fun(commands.Cog): def __init__(self, client): self.client = client def setup(client): client.add_cog(Fun(client))
import tkinter class Display(object): def __init__(self , W , H , background): self.window = tkinter.Tk() self.width = W self.height = H self.screen = self.window.geometry(str(W) + 'x' + str(H)) self.window.configure(background = background) def __repr__(self): ...