content
stringlengths
5
1.05M
# # @lc app=leetcode id=355 lang=python # # [355] Design Twitter # # https://leetcode.com/problems/design-twitter/description/ # # algorithms # Medium (26.90%) # Total Accepted: 32.4K # Total Submissions: 120.3K # Testcase Example: '["Twitter","postTweet","getNewsFeed","follow","postTweet","getNewsFeed","unfollow",...
#!/usr/tce/bin/python import sys import random if len(sys.argv) < 2 : usage = ''' usage: add_overlap.py list_base_name number_of_lists overlap_percent example: if your lists are t0_list.txt, t1_list.txt and t2_list.txt you want 30 percent overlap you would run as: add_overlap.py list....
import config class Snapp: info = { "genus": "", "family": "", "region": "", "source": "", "country": "", "binomial": "", "province": "", "difficulty": "", "photographer": "", "path": "" }, project_id: '' @staticmethod ...
# -*- coding: utf-8 -*- """ tasks.email ~~~~~~~~~~~ :author: Dave Caraway :copyright: © 2014-2015, Fog Mine LLC :license: Proprietary, see LICENSE for more details. """ from flask.ext.mail import Message from ..framework.extensions import mail, celery @celery.task() def send_email(message): m...
# -*- coding:utf-8 -*- from functools import reduce from pyfunctor.functor import Functor class Maybe(Functor): '''Maybe(value) -> new Functor object Example: >>> f = lift(lambda x, y: x + y) >>> run(f(Just('a'), Just('b'))) Just('ab') >>> run(f(Just(0), Nothing)) Nothing ''' def...
#!/usr/bin/env python3 """ Copyright (c) 2015 Jacob Martin A command for sending TauNet Messages. """ import sys import os import socket from subprocess import call from taunet import * args = sys.argv # Helpful usage hints. if len(args) != 3: print("usage:") print("\tpython3 client.py <username> <message>") ex...
""" zhihu.items ~~~~~~~~~~~ This module implements the items for zhihu scraping. :copyright: (c) 2017 by Jiale Xu. :date: 2017/11/04. :license: MIT License, see LICENSE.txt for more details. """ from lib.basis import SocialMediaItem, Sex class ZhihuItem(SocialMediaItem): pass class ZhihuUserItem(ZhihuItem): ...
import csv import random import math import operator import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA random.seed(123) # loadDataset and create training set and test set def load_data(filename, split, trainingSet, testSet): with open(filename, 'rb') as csvfile: ...
from src.utils.box_utils import iou, area, intersection, encode, batch_decode from src.utils.nms import batch_non_max_suppression
import logging import discord from core import MemberDataController from discord.ext import commands from discord.ext.commands.errors import BadArgument from main import SEBot from utils.custom_errors import AlreadyLiked from utils.utils import DefaultEmbed from ..utils.converters import Reputation, InteractedMember ...
import re import pytest import treedb @pytest.mark.parametrize('section, option, expected', [ pytest.param('core', 'name', True, id='section=core, option=name'), pytest.param('core', 'spam', False, id='section=core, option=unknown'), pytest.param('spam', 'core', False, ...
from os import environ from unittest.mock import call, patch import pytest from pytest import raises from vang.nexus3.publish import get_pom_publish_name from vang.nexus3.publish import get_publish_data from vang.nexus3.publish import main from vang.nexus3.publish import parse_args from vang.nexus3.publish import pub...
#!/usr/bin/env python2 # -- coding: utf-8 -- import requests import json import utils url = utils.API_URL token = utils.get_api_key() headers = utils.get_headers(token) user = "NYWFOIL" #<--- Put username here. Case sensitive. page = 1 next_ = url+"foia/?user="+user while next_ is not None: print "URL I'm usi...
import requests from requests import ConnectionError import pika import re import sys import time import json import HFRequests import os import math import pandas as pd import docker ready_response_text = 'Done!' controller = 'chainfaas.com' # controller = 'chainfaas.sara-dev.com' # controller_temp = 'chainfaas.sara-...
from .main import Auth from .jwt import JWT from .settings import Alerts from .settings import BaseConfig from .settings import TemplateConfig from .schemas import User __all__ = ["Auth", "JWT", "Alerts", "BaseConfig", "TemplateConfig", "User"]
import os.path as path import os import sqlite3 import argparse from datetime import datetime, timedelta def int_to_bytes(x: int) -> bytes: return x.to_bytes((x.bit_length() + 7) // 8, 'big') def int_from_bytes(xbytes: bytes) -> int: return int.from_bytes(xbytes, 'big') folder_path = path.join(os.environ[...
"""Generate gif from physics in Spriteworld config. This script runs the environment on a config in writes a video of the image observations. To run this script a config, run this on the config: ```bash python generate_gif.py --config=$path_to_task_config$ ``` If the config's colors are defined in HSV space, add the...
from setuptools import setup, find_packages setup( name="tamade", version="0.1.0", description="Get PHP settings from c source code.", long_description=""" tamade is a simple tool that will grab all the php ini settings from source code. Source code: https://github.com/mike820324/tamade Documentation...
from schema import And class DATAGRABMODE: NONE = 0 EVENTS = 1 JSON = 2 CFG_FOLDER = ".demomgr" CFG_NAME = "config.cfg" DEFAULT_CFG = { "datagrabmode": 0, "date_format": "%d.%m.%Y %H:%M:%S", "demopaths": [], "evtblocksz": 65536, "__comment": "By messing with the firstrun parameter you acknowledge " "the dis...
from comvest.extract_courses import extrair_cursos from comvest.extract_courses import dict_cursos def main(): extrair_cursos.extraction() dict_cursos.get() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import tensorflow.compat.v1 as tf import numpy as np T = tf.float64 log2pi = tf.cast(tf.math.log(2.0 * np.pi), T) def int_log2pi(k): return tf.cast(k, T) * tf.cast(tf.math.log(2.0 * np.pi), T) def loggaussian(x, mean=tf.cast(0.0, T), std=tf.cast(1.0, T)): return -0.5 * tf.reduce_s...
from sudoku_grid_detector import SudokuGridDetector from sudoku_digit_recognizer import SudokuDigitRecognizer_CV from sudoku_solver import SudokuSolver from matplotlib import pyplot as plt import numpy as np import cv2 import glob import os import time def processImage(img_filepath : str, tilesize_px : int) -> np.nda...
"""Current bezpy version.""" __version__ = '0.0.2'
import weakref import gc class C(object): def foo(self): print "inside foo()" def fact(n): if n <= 1: return n return n * fact(n-1) def getWR(): c = C() wr = weakref.proxy(c) wr.attr = "test attr" print wr.attr, c.attr wr.foo() del c return wr wr = getWR() fac...
# Do an experiment here. print("_file_begin_", "servo.txt") # Dump data logs here. It will be saved to "servo.txt". print("4,8037,2,0,2,1021,2,0,4500,38498") print("9,8037,2,0,2,1622,2,3,27000,41289") print("14,8051,2,0,2,1357,2,13,13500,43731") print("19,8051,2,0,2,1210,2,23,4500,46521") print("24,8044,2,0,2,2551,2,1...
import unittest from dcp.problems.bst.ds import BST from dcp.problems.bst.floor_ceiling import floor_ceiling1 class Test_FloorCeiling1(unittest.TestCase): def setUp(self): pass def test_case1(self): values, tree = [7, 5, 10, -1, 6, 25], BST() for v in values: ...
from slackbot.bot import Bot import logging import os def main(): logging.basicConfig(level=logging.INFO) logging.info("Running") bot = Bot() bot.run() if __name__ == "__main__": main()
from django.db import models from django.contrib import admin class Player(models.Model): name = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.name class Team(models.Model): name = models.CharField(max_length=200, unique=True, null=True, blank=True) players = models.ManyToMa...
import pytest from merchantsguide.commands import MineralQueryCommand, MineralUpdateCommand, NumberQueryCommand, NumeralUpdateCommand from merchantsguide.commands import UnknownCommand, BaseCommand from merchantsguide.registry import Registry def test_update_numeral(): r = Registry() r.reset() # add fou...
salario = float(input('Valor do salário: R$')) aumento = float(input('Valor do aumento (ex.: 5%): ')) r = salario * aumento / 100 salfinal = salario + aumento print(f'''Salário: R${salario:.2f} Aumento: {aumento:.1f}% → Salário final: R${salfinal:.2f}''')
import os from typing import Mapping from flask import Flask def create_app(test_config: Mapping = None) -> Flask: app = Flask(import_name='app', instance_relative_config=True) if test_config is None: # load the instance config from ../instance/config.json try: app.config.from_json...
"""Support for Atlantic Electrical Heater IO controller.""" import logging from typing import List from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATT...
# %% [markdown] # This is a simple notebook for H2O AutoMl prediction. # MLflow used as tracking tool since experiments take long time complete # and it is hard to manage too many experiments. #%% # Importing necessary libraries import os import pandas as pd from sklearn.model_selection import train_test_split import ...
""" Solution to HSPT 2017 - Naughty or Nice Solution idea - On a particular day, we can easily determine which house is the first and the last house to be pranked using simple math in constant time. Unfortunately, we can not update all the houses in the range because with the large bounds of the problem, t...
""" Tasks for the grades app """ import logging from celery import group from celery.result import GroupResult from django.contrib.auth.models import User from django.core.cache import caches from django.db import IntegrityError from django.db.models import OuterRef, Exists from django_redis import get_redis_connectio...
# Something import os import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd # Magic to get the library directory properly sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from common import moving_average def suq_curve(q, N, A, kc, gamma): return (N/A) / (kc*q**4...
#!/usr/bin/env python import collections from PyQt4 import QtCore, QtGui class Notification(QtGui.QWidget): aboutToClose = QtCore.pyqtSignal() contentChanged = QtCore.pyqtSignal() def __init__(self, text, parent, timeout=None, icon=None, links=None, recyclable=None): super(Notification, ...
from flask import Flask, url_for, redirect, json, request, make_response, Response, stream_with_context import atp_classes, os, gzip, glob app = Flask(__name__) config = atp_classes.Config() app.secret_key = config.get_config()['session_secret'] cache = atp_classes.Cache() app_db = atp_classes.AppDB() hive_db ...
def progress(count, total, suffix=''): bar_len = 60 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (bar_len - filled_len) if percents < 100: print('\r[{}] {}{} ...{}'.format(bar, percents, '%', suffix)...
# 入力 N, M = map(int, input().split()) # (等比*等差)数列の和の公式を用いる ans = (100 * N + 1800 * M) * 2**M # 出力 print(ans)
#!/usr/bin/env python from optparse import OptionParser import os import subprocess import shutil import logging import signal import re pwd = os.path.abspath(os.path.dirname(__file__)) vedir = os.path.abspath(os.path.join(pwd, "ve")) def kill_daemons(sig=signal.SIGKILL): uid = os.getuid() cmd = ['ps', 'x',...
# Copyright cocotb contributors # Licensed under the Revised BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-3-Clause import ctypes import pytest import cocotb.utils class TestHexDump: def test_int_illegal(dut): # this used to be legal, but deliberately is no longer with pyt...
import pytest from determined.experimental import Determined, ModelSortBy from tests import config as conf from tests import experiment as exp @pytest.mark.e2e_cpu def test_model_registry() -> None: exp_id = exp.run_basic_test( conf.fixtures_path("mnist_pytorch/const-pytorch11.yaml"), conf.tutori...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import logging logger = logging.getLogger(__package__)
#!/usr/bin/env python import roslib; roslib.load_manifest('wiimote') import rospy,math from sensor_msgs.msg import JoyFeedbackArray from sensor_msgs.msg import JoyFeedback from wiimote.msg import State siita=444 sp=2 past=State() def callback(data): global past,led0,led1,led2,led3,rum,siita,sp if not (data....
#encoding:utf-8 ''' @author: look @copyright: 1999-2020 Alibaba.com. All rights reserved. @license: Apache Software License 2.0 @contact: 390125133@qq.com ''' import os import re import sys,csv import threading import random import time import traceback BaseDir=os.path.dirname(__file__) sys.path.append(...
from qweNet.qweNet import * from data_util.generate_bc_feature import generate_bc_feature import networkx as nx import matplotlib.pyplot as plt import numpy as np import time from scipy.stats import kendalltau as kd import torch.optim as optim EMBEDDING_SIZE = 128 REG_HIDDEN = (int)(EMBEDDING_SIZE / 2) MIN_SIZE = 100 M...
import numpy as np import torch import torch.nn as nn import torch.autograd as autograd class RandomMirror(nn.Module): def __init__(self, mirror_prob): super(RandomMirror, self).__init__() self.mirror_prob = mirror_prob self.inv_idx = None def forward(self, x): input_size = x....
from django.utils.translation import ugettext_lazy as _ from mayan.apps.common.apps import MayanAppConfig from mayan.apps.common.menus import menu_object, menu_secondary, menu_tools from mayan.apps.navigation.classes import SourceColumn from .classes import StatisticLineChart, StatisticNamespace from .links import ( ...
import pytest from pathlib import Path from timeit import repeat from statistics import mean from ..json import dumps, JsonOpt, loads xfail = pytest.mark.xfail parametrize = pytest.mark.parametrize base = Path(__file__).parent / 'json_test_data' paths = [base/f for f in ('twitter.json', 'github.json')] def op...
# -*- coding: utf-8 -*- """ Created on Thu Mar 14 21:57:02 2019 @author: Ashwin """ import matplotlib.pyplot as plt import numpy as np cartesian_coordinates = np.load('data/cartesian_coordinates.npy') pixel_centers = np.load('data/pixel_centers.npy') image_squares = np.load('data/image_squares.npy') point_to_displ...
#!/usr/bin/env python #-*- coding:utf-8 -*- from lib.net import IP, TCP
from rest_framework.test import APIRequestFactory from rest_framework.reverse import reverse from django.db.models import Count from contentcuration.management.commands.setup import create_user from contentcuration.management.commands.setup import create_channel from contentcuration.models import User from contentcurat...
import csv import os import sys import cPickle import operator from cnn_text_trainer.rw import datasets __author__ = 'devashish.shankar' #TODO clean up this. Move to core maybe? def evaluate(data,outputf): """ Ported from initial version. TODO refactor to accept new format of data and clean up this code :...
HTK_FEEDBACK_EMAIL_SUBJECT = 'New feedback from Hacktoolkit form'
import numpy as np import matplotlib.pyplot as plt import math import vmath print(vmath) print(dir(vmath)) S = \ [ "vmath.sqrt_( 2 )", "vmath.sin_ ( 0 )", "vmath.cos_ ( 0 )", "vmath.tan_ ( 0 )", "vmath.sin_ (math.pi/4)", "vmath.cos_ (math.pi/4)", "vmath.tan_ (math.pi/4)", ] l...
from functools import reduce identity = lambda x: x is_truthy = bool NOTHING = '' def to_dict(named_tuple): return dict(zip(named_tuple._fields, named_tuple)) def enum_values(enum): return (member.value for member in enum) def get_enum_member(enum, value): for member in enum: if member.value == value: ...
import numpy as np import logging from multiprocessing import Pool, cpu_count logger = logging.getLogger(__name__) NCPUS = cpu_count() def get_frequency_grid(times, samplesperpeak=5, nyquistfactor=5, minfreq=None, maxfreq=Non...
import pandas as pd from datacode.typing import StrList from datacode.typing import IntOrNone from datacode.summarize.subset.missing.detail.textfuncs import ( missing_more_than_str, missing_more_than_pct_str, missing_tolerance_count_str, id_count_str ) def by_id_pct_long_df(df: pd.DataFrame, byvars: ...
from flask_script import Manager from resume import app, db, Professor, Course manager = Manager(app) # reset the database and create two artists @manager.command def deploy(): db.drop_all() db.create_all() monk = Professor(name='Ellen Monk', dept='MIS') bayley = Professor(name='Elizabeth Bayley', de...
from django.shortcuts import render import django_filters from django_filters.rest_framework import DjangoFilterBackend from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample from drf_spectacular.types import OpenApiTypes from rest_framework import viewsets, permissions, views, generics, stat...
from datetime import datetime from django.conf import settings from django.db.models import CharField, DateTimeField from jeevesdb.JeevesModel import JeevesModel as Model, JeevesForeignKey as ForeignKey from jeevesdb.JeevesModel import label_for import pytz from sourcetrans.macro_module import macros, jeeves import J...
# # Resource.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Base class for all resources # from Logging import Logging from Constants import Constants as C from Configuration import Configuration import Utils, CSE import datetime, random # Future TODO: ...
# see table at page 26 for the PDF document # GUIDA ALLA COMPILAZIONE DELLE FATTURE ELETTRONICHE E DELL’ESTEROMETRO # from AdE (Agenzia Delle Entrate), version 1.6 - 2022/02/04 # https://www.agenziaentrate.gov.it/portale/documents/20143/451259/Guida_compilazione-FE_2021_07_07.pdf/e6fcdd04-a7bd-e6f2-ced4-cac04403a768 # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 10 12:50:59 2020 @author: Luke """ #============================================================================== # SUMMARY #============================================================================== # 18 May 2020 # plots maps of climate ch...
from django.db import models class ReportUser(models.Model): user_id = models.CharField(max_length=250) reported_by = models.CharField(max_length=250) reason = models.CharField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True) class CreateShopRecommendation(models.Model): use...
from random import choice class Comparator: def compare(self, clients, table): return [choice(list(clients.keys()))]
import unittest import tempfile import shutil import numpy as np import os from dicomml.cases.case import DicommlCase from dicomml.tasks.main import run_task from tests import sample_case_config class TestLTS(unittest.TestCase): def get_config(self): from ray import tune scheduler = tune.sched...
au2fs = 2.41888432651e-2 # femtoseconds au2as = 24.1888432651 # attoseconds au2k = 315775.13 #K au2ev = 27.2116 au2kev = 27.2116e-3 au2mev = 27.2116e3 au2wn = au2wavenumber = 219474.6305 wavenumber2hartree = wavenum2au = 4.55633525277e-06 ev2wavenumber = 8065.73 au2debye = 2.541765 # hbar^2/(m_e * e) au2nm = bohr2...
# Copyright (c) 2018 Ansible, Inc. # All Rights Reserved. from ansiblelint import AnsibleLintRule class NoTabsRule(AnsibleLintRule): id = '203' shortdesc = 'Most files should not contain tabs' description = 'Tabs can cause unexpected display issues. Use spaces' tags = ['formatting'] def match(se...
# -*- coding: utf-8 -*- from textlytics.sentiment.lexicons import SentimentLexicons
""" ############################################################################## PyDraw 1.1: simple canvas paint program and object mover/animator. Uses time.sleep loops to implement object move loops, such that only one move can be in progress at once; this is smooth and fast, but see the widget.after and thread-ba...
""" *F♯ - Level 8* """ from ..._pitch import Pitch __all__ = ["Fs8"] class Fs8( Pitch, ): pass
# This code is auto-generated. import http.client as http_client import logging import os import numpy as np from joblib import load from scipy import sparse from sagemaker_containers.beta.framework import encoders from sagemaker_containers.beta.framework import worker from sagemaker_sklearn_extension.externals impor...
import torch.optim as optim import torch.nn as nn from dl_modules.metric.psnr import PSNR from dl_modules.metric.ssim import SSIM from lpips import LPIPS from dl_modules.loss import VGGPerceptual, LSGANGenLoss, \ LSGANDisLoss, LSGANDisFakeLoss, LSGANDisRealLoss gen_opt_state_dict = None dis_opt_state_dict = None ...
# :coding: utf-8 import os.path import click import synes @click.command() @click.argument("width", type=int) @click.argument("input_path", type=click.Path(exists=True)) @click.option("-o", "--output_path", type=click.Path()) def main(input_path, width, output_path): ext = os.path.splitext(input_path)[1] i...
"""PDB2PQR Version number. Store the version here so: * we don't load dependencies by storing it in :file:`__init__.py` * we can import it in setup.py for the same reason * we can import it into your module """ __version__ = "3.5.0"
# encoding: utf-8 import re from sect import cluster from lxml.html import fromstring # we expect you to override in response to necessary. # but need customize not necessarily. def not_body_rate(block): # not_body_rate() takes account of not_body_rate. # return value has to be float or integer. return 0 ...
from assay_interchange import app from flask import request from assay_interchange.lib import convert_data, validate_data @app.route('/', methods=['GET']) def index(): return app.send_static_file('index.html') @app.route('/', methods=['POST']) def index_post(): return convert_data(request) @app.route('/va...
'''this module make main color tint and shade then return it as hex color.''' import typing from random import randint def make_Tint(color: str, percent: int) -> str: percent = abs(percent) if percent > 100: raise ValueError('percent must be between 0 and 100') color = color.lstrip('#') rgb =...
import sys sys.path.append('../') from geometry_translation.options.train_options import TrainOptions from geometry_translation.utils.visualizer import Visualizer from geometry_translation.models import create_model from geometry_translation.data_loader import get_data_loader from datetime import datetime import os c...
# type: ignore[misc] """Custom widgets for yt-dlg""" # -*- coding: future_annotations -*- from datetime import timedelta from pathlib import Path from typing import TYPE_CHECKING, Callable import wx import wx.lib.masked as masked from .darktheme import DARK_BACKGROUND_COLOUR, DARK_FOREGROUND_COLOUR, dark_mode from ....
""" Emits top.v's for various BUFHCE routing inputs. """ import os import random random.seed(int(os.getenv("SEED"), 16)) from prjxray import util from prjxray.lut_maker import LutMaker from prjxray.db import Database from io import StringIO CMT_XY_FUN = util.create_xy_fun(prefix='') def read_site_to_cmt(): """ Y...
import mock import pytest import requests from wristband.providers.exceptions import DeployException from wristband.providers.service_providers import DocktorServiceProvider @mock.patch.object(DocktorServiceProvider, 'get_docktor_server_config') @mock.patch('wristband.providers.service_providers.requests') @mock.pat...
from nanome.util import Vector3, Quaternion, Logs from . import _Base from . import _helpers class _Complex(_Base): @classmethod def _create(cls): return cls() def __init__(self): super(_Complex, self).__init__() #Molecular self._name = "complex" self._index_tag = ...
#!/usr/bin/env python #encoding=utf8 if __name__ == "__main__": infile="/home/anthonylife/Doctor/Data/Douban/Event/eventInfo.csv" outfile = "/home/anthonylife/Doctor/Code/MyPaperCode/EventRecommendation/data/doubanEventInfo.csv" wfd = open(outfile, "w") for line in open(infile): line = line.rep...
# # PySNMP MIB module CISCO-IETF-SCTP-EXT-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-SCTP-EXT-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 12:01:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
from amaranth.build import * import warnings warnings.warn("instead of nmigen.build, use amaranth.build", DeprecationWarning, stacklevel=2)
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render, redirect from django.urls import reverse class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ # print(modulen...
import shlex import subprocess p = subprocess.Popen(shlex.split('sudo echo 1'), stdout=subprocess.PIPE) p = subprocess.Popen(shlex.split('sudo echo 1'), stdout=subprocess.PIPE)
def readConfig(configName="config.txt"): """ Reads the information from configuration file (config.txt) Returns the following information in a list: 1) The name of the Excel file containing the designated Excel sheet 2) The name of the Excel sheet to read the data from 3) The name of the Word do...
import wrapt def keyword_optional(keyword, before=False, after=False, keep_keyword=False, when_missing=False): """Execute a function before and after the decorated function if the keyword is in the kwargs Examples: def do_thing(): # ... does something ... ...
import json from loguru import logger from spade.behaviour import State, FSMBehaviour from simfleet.customer import CustomerStrategyBehaviour from simfleet.fleetmanager import FleetManagerStrategyBehaviour from simfleet.helpers import PathRequestException, distance_in_meters from simfleet.protocol import REQUEST_PERF...
"""Instruction running module.""" # Official Libraries # My Modules from sms.objs.basecode import BaseCode from sms.syss import messages as msg from sms.utils.log import logger __all__ = ( 'apply_instructions', ) # Define Constants PROC = 'INST RUNNER' # Main def apply_instructions(base_data: l...
import sys import itertools from packet import * from program import * class Parser(): def __init__(self, filename): self.warp_size = 4 self.dimensions = [] self.tg_thread_counter = 0 self.threadgroup_start_index = {} self.threadgroup_end_index = {} self.threadgr...
#!/usr/bin/env python from itertools import imap import logging import os.path import sqlite3 import sys from tilecloud import Tile, TileCoord, consume from tilecloud.filter.error import DropErrors from tilecloud.filter.logger import Logger from tilecloud.store.mbtiles import MBTilesTileStore from tilecloud.store.ren...
from django.test import TestCase from account.models import User from main.constants import LANGUAGES from main.models import Comment, Snippet, Tag, Ticket class SnippetTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: cls.sample = { 'title': 'simple title', 'd...
from pycparser import c_parser, c_ast, c_generator from copy import deepcopy def rename_function_calls(): pass def remove_input_port(func_def, ele_name, inports): func_def.decl.name = ele_name func_def.decl.type.type.declname = ele_name stmts = func_def.body.block_items new_stmts = [] port2arg...
### DAY 2 ### ### TASK 1 ### # I downloaded and saved the input file as a .txt because I was getting a 400 Bad Request Error when trying to open it with urllib.request.urlopen f = open("input.txt", "r") raw_input = f.read() # I want to convert my input into 3 lists corresponding to up, down and forward. # I can do it ...
import torch.nn as nn class Discriminator(nn.Module): def __init__(self, input_dim, wasserstein=False): super(Discriminator, self).__init__() self.model = nn.Sequential( nn.Linear(input_dim, 2 * input_dim // 3), nn.LeakyReLU(0.2), nn.Linear(2 * input_dim // 3, i...