content
stringlengths
5
1.05M
class Relation(object): """ A child Elements of this Element :param fqn: FQN of the other Element :type name: string """ def __init__(self, fqn): self.fqn = fqn
from yaml import load, safe_dump from time import time, sleep from hashlib import sha1 from os.path import exists, basename from stompy.simple import Client from M2Crypto.RSA import load_key __version__ = '0.4' class AlreadySentException(Exception): pass class Config(object): def __init__(self, configfile=...
# This script can be used for the following: # 1. aruco marker detection with Realsense camera (set socket_connect = 0 to test Realsense tracking Aruco pose only) # 2. calibrate the realsense and AR headset spaces using marker 1, and test the calibration by tracking an Aruco marker (set socket_connet = 1). This can be ...
#!/usr/bin/env python3 import urllib.request import urllib.parse import json version = "1.0.2" def listDevices(apikey): reg = urllib.request.urlopen("https://joinjoaomgcd.appspot.com/_ah/api/registration/v1/listDevices?apikey=" + apikey) return json.loads(reg.read().decode("utf-8")) def request(args): #...
from django.shortcuts import render, redirect,get_object_or_404 from .models import Image,Location,Category from django.http import HttpResponse, Http404 import datetime as dt from django.core.exceptions import ObjectDoesNotExist # Create your views here. def photos(request): category=request.GET.get('category') ...
import smbus import time light_sensor = 0x23 # I2C address Power_down = 0x00 # No active state Power_on = 0x01 # Power on Reset = 0x07 # Reset data register value # Start measurement at 1lx resolution. Time typically 120ms #measures at 1lx resolution, time = 120ms #devices automacally powers down after meas...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-10-28 08:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commercialoperator', '0095_auto_20201028_1454'), ] operations = [ migration...
from django.apps import AppConfig class WishesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'wishes'
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from sdataflow.shared import to_unicode from .lexer import create_lexer from .parser import create_parser from .analysis import Dataflow __all__ = ['parse'] # input: `doc` with type ...
import sys import tfcochleagram import tensorflow as tf import numpy as np import scipy.io.wavfile as wav import pickle import sys import json import os import scipy import matplotlib.pylab as plt import audio_cnn_helpers import metamer_helpers # Jittered relu grad is only applied to the metamer generation layer. ...
from django.db import models class SVM(models.Model): gamma = models.FloatField() c = models.FloatField() coef0 = models.FloatField() kernel = models.CharField(max_length=32) class Algorithm(models.Model): name = models.CharField(null=True, max_length=128) svm = models.ForeignKey(SVM, null=T...
"""Document Structure Parser. This module contains a minimal document structure parser. It is meant as a temporary default and will be replaced by more sophisticated parsers and these parsers will act more like the other tarsqi components. The main goal of the parser is to add docelement tags to the tag repository on...
from abc import ABC, abstractmethod import numpy as np class BaseMixingAdjuster(ABC): """ A class used to build a time-varying mixing matrix adjustment. This could be adjusted according to the age or the location structure of the model's contact matrices. """ @abstractmethod def get_adjustm...
import os import typing from cfg_exporter.const import TEMPLATE_EXTENSION, DataType from cfg_exporter.exports.base.export import BaseExport from cfg_exporter.lang_template import lang ERL_EXTENSION = 'erl' HRL_EXTENSION = 'hrl' BASE_TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'template', ERL_EXTENSION) ER...
from .cause import * from .campaign import * from .volunteer import *
#!/usr/bin/env python # Copyright 2011-2021 IBM Corporation # # 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...
""" 将列表中的数字累减 list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] 结果:806400 """ list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] result = list02[0] for i in range(1, len(list02)): result -= list02[i] print(result)
from gooey import Gooey, GooeyParser @Gooey(program_name='Hello') def main(): parser = GooeyParser(description='A Demo') parser.add_argument('path', widget='FileChooser') parser.add_argument('date', widget='DateChooser') args = parser.parse_args() print(args) if __name__ == '__main__': main(...
import streamlit as st import numpy as np import pandas as pd import geopy import matplotlib.pyplot as plt from similarity import rank_courses, convert_df, convert_prefs def _max_width_(): """ Increase Streamlit app width to fullscreen. Fom https://discuss.streamlit.io/t/custom-render-widths/81/8 """...
# coding: utf-8 """ This file contains tests for Cursor class. """ import json from pytest import fixture from mock import Mock from pysqlcollection.cursor import Cursor @fixture(scope=u"function") def cursor(): return Cursor( Mock(), Mock(), Mock(), Mock() ) def test_deduplicate_lookup(cursor): ...
from setuptools import setup setup( name='main', version='0.0.1', entry_points={ 'console_scripts': ['toolshed=main:run'] } )
import responses from rest_framework import status, test from waldur_core.structure.tests.factories import UserFactory class RemoteCustomersTest(test.APITransactionTestCase): @responses.activate def test_remote_customers_are_listed_for_given_token_and_api_url(self): responses.add(responses.GET, 'http...
# -*- coding: utf-8 -*- from __future__ import print_function, division import logging from datetime import datetime, timedelta log = logging.getLogger('openweather') url = 'http://openweathermap.org/data/2.1/find/name?q=%s' def init(bot): global default_location global threshold config = bot.config.get...
from torchvision.datasets.utils import download_and_extract_archive replica_url = 'https://docs-assets.developer.apple.com/ml-research/datasets/gsn/replica.zip' data_dir = '/media/data1/replica/' download_and_extract_archive(url=replica_url, download_root=data_dir)
""" Configuration provider to fetch values from the following sources: - Environment variables - AWS Systems manager (SSM) Parameter store """ import os import logging from app_handler.service.aws import AwsService class ConfigProvider: """ Configuration provider class """ def __init__(self) -> None: ...
import copy import torch from torch import nn import os import numpy as np from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F CACHE_SIZE=100 class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequen...
# -*- coding: utf-8 -*- from __future__ import unicode_literals class DisqusAPIError(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message
""" This is a module to predict the background levels for JWST observations, for use in JWST proposal planning. It accesses a precompiled background cache prepared by STScI, to do the following: - Plot the background versus calendar day. - Compute the number of days per year that a target is observable at low backgrou...
#! /usr/bin/env python import sys import unittest def run_tests(): test_suite = unittest.TestLoader().discover('dcm_spec_tools') result = unittest.TextTestRunner(verbosity=2).run(test_suite) return result.wasSuccessful() if __name__ == '__main__': sys.exit(0 if run_tests() else 1)
# -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2018 Bitcraze AB # # Th...
from aiogram import exceptions as aiogram_exceptions, types from typing import Optional import NekoGram async def menu_callback_query_handler(call: types.CallbackQuery): neko: NekoGram.Neko = call.conf['neko'] call_data: Optional[int] = None new_call_data: str = call.data if '#' in call.data: # If d...
from django.db import models class Post(models.Model): title = models.CharField(max_length=128) link = models.URLField(max_length=256) creation_date = models.DateField(auto_now_add=True) upvotes = models.IntegerField(default=0) author = models.CharField(max_length=128) class Meta: ord...
from datetime import datetime as dt, timedelta as td from models.channel import Channels from config import CACHE_INTERVAL class ChannelsCache(): def __init__(self, cache_interval: td) -> None: # self.channels = None self.simplifyChannels = None self.rooms = None self.cache_interva...
""" GameBoy Emulator Written in Python MIT License Copyright (c) 2017 Ryan Sheffer 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 the rights to...
# MIT License # --- # Microprocessor Systems Lab Project # --- # Program purpose: Serial communication class. # --- # @author: Krzysztof Stezala # --- # Institute of Control, Robotics and Information Engineering of # Poznan University of Technology # dependecies import sys import glob import serial class SerialComm...
# coding: utf-8 f = open("SentiWordNet_3.0.0_20130122.txt","r") for line in f: splitline = line.rstrip().split("\t") words = map(lambda x: x[:-2],splitline[4].split(" ")) print(words) my_dict = dict() for line in f: splitline = line.rstrip().split("\t") words = map(lambda x: x[:-2],splitline[4]...
# # PySNMP MIB module APPACCELERATION-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-TC # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
#!/usr/bin/python -tt """NetSPOT - Network SPOT Interact with the netspot database. """ from datetime import datetime from spotmax import SpotMAX from network_device import NetworkDevice import netspot_settings class Asset(object): """Class to represent an asset.""" def __init__(self, asset, ...
""" ## AWS CDK Assets <!--BEGIN STABILITY BANNER-->--- ![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge) > The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward com...
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doctype('User') for d in frappe.get_all("Employee"): employee = frappe.get_doc("Employee", d.name) if employee.company_email: employee.prefered_contact_email = "Company Email" employee.prefered_email = employee.company_email...
# # Modified by Peize Sun, Yi Jiang # Contact: sunpeize@foxmail.com # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ OneNet Transformer class. Copy-paste from torch.nn.Transformer with modifications: * positional encodings are passed in MHattention * extra LN at the end of encoder i...
from amitools.vamos.machine import MockMemory from amitools.vamos.libnative import InitStruct, InitStructBuilder def init_struct_test(): mem = MockMemory() # setup init table init_tab = 0x100 mem_ptr = 0x200 ib = InitStructBuilder(mem, init_tab) ib.init_byte(0, 21) ib.init_word(12, 0xDEAD)...
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
from __future__ import (absolute_import, division, print_function) import shlex from plumbum import local from plumbum.commands.processes import ProcessExecutionError from playbook.actions import BaseAction class Action(BaseAction): name = u'script' def handler(self): for cmd in self._args: ...
from django.urls import path, include from . import views app_name = 'dogcatapp' urlpatterns = [ path('', views.dogcatform, name='dogcat_form'), ]
#!/usr/bin/env python # DL2 to IRFs stage for the R0 to IRFs full MC production workflow. # As all the previous stages, this script make use of the lstchain entry points to batch each workflow stage. import os import shutil import logging from pathlib import Path from lstmcpipe.workflow_management import save_log_to_...
#!/usr/bin/env python """ Given output from PRESTO's single_pulse_search.py routine, plot those events in an interactive session. """ __version__ = '0.1' __revision__ = '1' __author__ = 'Bradley Meyers\nSteven Tremblay' import os import wx import pandas import matplotlib matplotlib.use('WXAgg') matplotlib.interacti...
# Generated by Django 3.0.4 on 2020-12-11 15:17 import classes.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import martor.models import simple_history.models class Migration(migrations.Migration): initial = True dependencies = [ (...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2009- Spyder Project Contributors # # Distributed under the terms of the MIT License # (see spyder/__init__.py for details) # ---------------------------------------------------...
# -*- coding: utf-8 -*- """ Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. """ from collections import defaultdict class Solution: # @par...
import setuptools import setuptools.command.build_py import distutils.cmd import distutils.command import os import re import subprocess def concat( dirname, filename ): return dirname + "/" + filename def crawl( dirname ): dirs = [ concat( dirname, d ) for d in os.listdir( dirname ) if os.path.isdir( concat(...
# coding: utf-8 from django.shortcuts import render from RecruitManage.models import Recruitment from TaskManage.models import Task from TaskManage.views import task_status def home(request): template = 'home.html' recruitment_list = Recruitment.objects.all()[:4] task_list = Task.objects.filter(task_sta...
from snovault.schema_utils import validate import pytest targets = [ {'name': 'one', 'uuid': '775795d3-4410-4114-836b-8eeecf1d0c2f'}, ] @pytest.fixture def content(testapp): url = '/testing-link-targets/' for item in targets: testapp.post_json(url, item, status=201) def test_uniqueItems_valida...
import os import tensorflow as tf def get_files(dir): paths = [] files = [] path = os.path.expanduser(dir) for file in os.listdir(path): paths.append(os.path.join(path, file)) files.append(file.split(".")[0]) return paths, files def dataset(image_files, files): def decode_image(image_file): ...
import warnings import matplotlib.pyplot as plt from matplotlib.figure import Figure import pandas as pd import numpy as np import json warnings.filterwarnings("ignore") class PatternFinder: def cosine_similarity(self,x,y): return np.dot(x,y) / (np.sqrt(np.dot(x,x)) * np.sqrt(np.dot(y,y))) def __init__...
import os import sys import inspect class PluginManager(object): PLUGINS = {} def after_setup(self, plugins=(), *args, **kwargs): return self._run_func(plugins, *args, **kwargs) def after_init(self, plugins=(), *args, **kwargs): return self._run_func(plugins, *args, **kwargs) def _r...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minCameraCover(self, root: TreeNode) -> int: cache = collections.defaultdict(int) inf = ...
import json import os import dash import dash_core_components as dcc import dash_html_components as html import zmq from dash.dependencies import Input, Output from util import * params = {'ready': 0, 'posUpperLimit': 0, 'posLowerLimit': 0, 'spread': 10.0, 'buysellSkew': 0.0, ...
#Instance Template COMPUTE = 'https://www.googleapis.com/compute/v1' def GenerateConfig(context): project = '/projects/' + context.properties['project'] resources = [{ 'name': context.env['name'], 'type': 'compute.v1.instanceTemplate', 'properties': { 'pr...
import matplotlib.pyplot as plt import pandas as pd from pyautogui import alert, confirm, prompt from sklearn.linear_model import LinearRegression def predicts(df, X, y, x_label, y_label): model = LinearRegression() model.fit(df[[X]], df[[y]]) # ask a value to predict predict_value = int( inpu...
import warnings from copy import copy from typing import Dict, List, Tuple, Union import numpy as np from vispy.color.colormap import Colormap from ...types import ValidColormapArg from ...utils.colormaps import ensure_colormap_tuple from ...utils.event import Event from ...utils.status_messages import format_float f...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('accounting', '0003_auto_20141127_1450'), ] operations = [ migrations.RemoveField( model_name='ch...
"""Quick plotting.""" # --- import -------------------------------------------------------------------------------------- import os import numpy as np import matplotlib.pyplot as plt from ._helpers import _title, create_figure, plot_colorbar, savefig from ._colors import colormaps from .. import kit as wt_kit ...
from Grupito import * def test_group_score(): stuA = Student("stuA", is_online=False) stuB = Student("stuB", is_online=True) stuC = Student("stuC", is_online=True) histoAB = Group([stuA, stuB]) histoAC = Group([stuA, stuC]) grp = Group([stuA, stuB, stuC]) grp_score = GroupScore...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-05-01 Last_modify: 2016-05-01 ****************************************** ''' ''' Implement a basic calculator to evaluate a...
#import random; class AgentSim: def InitializeAgent(self): return 0; name = "Example Agent 1"; north = 0; east = 0; south = 0; west = 0; latestX = 0; latestY = 0; def UpdateAgentMove(self): randomChoice = 1;#randint(1,5);...
# -*- coding: utf-8 -*- # Copyright (c) 2004-2015 Odoo S.A. # Copyright 2018-2019 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr> # License MIT (https://opensource.org/licenses/MIT). import logging from datetime import datetime from odoo import _, api, exceptions, fields, models from odoo.tools imp...
import unittest from dash.map import TileMap, Objects, Object class TestObjectMap(unittest.TestCase): def test_window(self): tile_map = TileMap((10, 10)) tile_map.set_outside(1, 0, 0, 0) object_map = Objects(tile_map) object_map.add_object("obj", (2.5, 2.5)) object_map.a...
#!/usr/bin/env python from numpy import * from datetime import datetime,timedelta from netCDF4 import Dataset import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors from bisect import bisect_left, bisect_right import scipy import copy er = 6371.0 #km def date_interpolation(da...
class ArrayUtils: @staticmethod def amin(array, axis=None): if axis is None: return min([min(r) for r in array]) if axis == 0: return [min(c) for c in zip(*array)] if axis == 1: return [min(r) for r in array] @staticmethod def amax(array, axis...
HTK_COMPANY_EMAIL_DOMAINS = () HTK_COMPANY_OFFICER_EMAILS = () HTK_COMPANY_EMPLOYEE_EMAILS = () HTK_EMULATE_USER_COOKIE_EXPIRATION_MINUTES = 15
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: NetworkRanger # Date: 2019/8/11 1:53 PM # admin.py from django.contrib import admin from blog import models class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'timestamp') admin.site.register(models.BlogPost, BlogPostAdmin)
import numpy as np from numpy import linalg as LA from .utils import compute_kmeans_centroids, compute_cost_matrix class FC: def __init__(self, n_anchors, epsilon=1, floyditer=50, tolratio=1e-7, norm=2, random_state=None): self.n_anchors = n_anchors self.epsilon = epsilon self.niter = fl...
from uuid import UUID, uuid4 from abc import ABCMeta, abstractmethod class Request(metaclass=ABCMeta): def __init__(self) -> None: self._requestid = uuid4() @property def id(self) -> UUID: return self._requestid @staticmethod @abstractmethod def is_aCommand() -> bool: ...
from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.stockticker print(db.list_collection_names()) glob = db.globalsymbols sym = "TSLA" price= "400" res = glob.find_one({'symbol': sym}) print(res['triggers'])
from copy import deepcopy from operator_generator_strategies.base_generator_strategy import BaseGeneratorStrategy from operator_generator_strategies.distinct_operator_strategies.distinct_aggregation_strategy import \ DistinctAggregationGeneratorStrategy from operator_generator_strategies.distinct_operator_strategi...
from signal import pause import cv2 from pitop import Camera from pitop.processing.algorithms.faces import EmotionClassifier, FaceDetector def detect_emotion(frame): face = face_detector(frame) emotion = emotion_classifier(face) if emotion.found: print(f"{emotion_lookup[emotion.type]}", end="\r...
import requests import xmltodict, json import json query = "http://mygene.info/v3/query?q=symbol:" d = {} with open('universe.txt', mode='r') as in_file, \ open('universeid.txt', mode='w') as out_file: for g in in_file: response = requests.get(query+g) json_data = json.loads(respon...
from estudent import data_generator from estudent.school import School def run_example(): students = data_generator.generate_students() school = School(name="Hogwart", students=students) print(school) new_students = data_generator.generate_students(number_of_students=8) school.students = new_stud...
import pytest from conftest import fail_on_pvlib_version, platform_is_windows, has_python2 # allow xpass for python 2 on windows @pytest.mark.xfail(strict=(not (platform_is_windows and has_python2)), reason='fail_on_pvlib_version should cause test to fail') @fail_on_pvlib_version('0.0') def test_f...
from abc import abstractmethod class Command(object): @abstractmethod def do(self): pass class UndoableCommand(object): @abstractmethod def undo(self): pass class CommandManager(object): def __init__(self, stack): self.stack = stack def execute(self, command): ...
import tensorflow as tf class MultiLayerPerceptron(object): """ A layer for mapping embeddings from different embedding spaces to the same shared embedding space. """ def __init__(self, hidden_layer_sizes, input_size, scope = "mlp_layer", unique_scope_addition = "_1"): self.input_size = input_size self.hidde...
import uuid from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.order_by(InboundNumber.updated_at).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, ...
import abc from gcg.envs.env_spec import EnvSpec class Env: """ What subclasses must implement """ @abc.abstractmethod def __init__(self, params={}): self.observation_im_space = None self.action_space = None self.action_selection_space = None self.observation_vec_spec = No...
from lua_token import * import re class Lexer: re_new_line = re.compile(r"\r\n|\n\r|\n|\r") re_identifier = r"^[_\d\w]+" re_opening_long_bracket = r"^\[=*\[" re_short_string = r"(?s)(^'(\\\\|\\'|\\\n|\\z\s*|[^'\n])*')|(^\"(\\\\|\\\"|\\\n|\\z\s*|[^\"\n])*\")" re_number = r"^0[xX][0-9a-fA-F]*(\.[0-9...
# -*- coding: utf-8 -*- from ..syntax import macros, test, test_raises # noqa: F401 from ..test.fixtures import session, testset from operator import add, mul from functools import partial from ..fold import (scanl, scanr, scanl1, scanr1, rscanl, rscanl1, foldl, foldr, reducel, reducer, rreducel...
import json import sys start_ts = None end_ts = None # start ai_main_thread_used_cpu_sys_start = None ai_main_thread_used_cpu_user_start = None ai_queue_CPU_bthread_n1_used_cpu_total_start = None ai_self_used_cpu_sys_start = None ai_self_used_cpu_user_start = None print( "Warning! This script was created to easi...
import os, sys from InquirerPy.utils import color_print from .async_tasks.randomize import Randomizer class Session: ''' this one's in charge of activating session-related tasks ''' failed_presences = 0 def __init__(self,client): self.client = client try: self.previ...
# -*- coding: utf-8 -*- # ZX Spectrum Emulator. # https://github.com/kosarev/zx # # Copyright (C) 2017-2019 Ivan Kosarev. # ivan@kosarev.info # # Published under the MIT license. import os import tempfile from ._data import File from ._data import FileFormat from ._error import Error class ZXBasicCompiler...
############################################################################## # # A simple example of merging cells with the XlsxWriter Python module. # # Copyright 2013, John McNamara, jmcnamara@cpan.org # from xlsxwriter.workbook import Workbook # Create an new Excel file and add a worksheet. workbook = Workbook('...
from . import * class AWS_Cloud9_EnvironmentEC2_Repository(CloudFormationProperty): def write(self, w): with w.block("repository"): self.property(w, "PathComponent", "path_component", StringValueConverter()) self.property(w, "RepositoryUrl", "repository_url", StringValueConverter()) class AWS_Cloud...
import json class User(object): def __init__(self, api_client): self.api_client = api_client def add_user(self, userid): data = {'userid': userid} response = self.api_client.session.post( self.api_client.get_server() + '/users/common/list/addUser', data) if respon...
# -*- coding: utf-8 -*- # 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 # "...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int: s = set(G) res = 1 prev = False while (head): ...
import numpy as np, time, copy import torch, torch.nn as nn from tqdm import tqdm from test import get_cross_preds, retrieve from utils import * def calc_class_weights(labels, eps=0.75): minority_class = 0 if sum(labels) > len(labels) / 2 else 1 minority_weight = len(labels) / sum(labels == minor...
# coding: utf-8 class InvalidToken(Exception): def __init__(self, method, url): message = u'{} {} returned 401 (seems like token is invalid)'.format(method, url) super(InvalidToken, self).__init__(message) class ResponseNotValidated(Exception): def __init__(self, method, url): mess...
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from rest_framework_simplejwt.tokens import RefreshToken # User manager for custom user model class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=No...
from typing import List from weaverbird.backends.mongo_translator.steps.types import MongoStep from weaverbird.pipeline.steps import SubstringStep def translate_substring(step: SubstringStep) -> List[MongoStep]: pos_start_index = ( step.start_index - 1 if step.start_index > 0 else {'$add'...
""" Prim's minimum spanning tree algorithm. This file job.txt describes an undirected graph with integer edge costs. It has the format [number_of_nodes] [number_of_edges] [one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost] [one_node_of_edge_2] [other_node_of_edge_2] [edge_2_cost] ... For example, the third lin...
import json import time import matplotlib.pyplot as plt from PIL import Image import requests img = Image.open('granadilla.jpg') plt.imshow(img) plt.show() addr = 'http://localhost:5000' test_url = addr + '/api/recognize' # prepare headers for http request # content_type = 'image/jpeg' # headers = {'content-type': c...